function - Lisp-在函数的多个语句中修改局部变量

标签 function variables if-statement lisp local

我是 lisp 的新手,试图了解 lisp 的工作原理,但我不知道如何在大型函数中使用局部变量。 在这里我有一点 exc,我将一个数字发送给一个函数,如果它可以被 3、5 和 7 整除,我必须返回一个列表(by3by5by7),如果只能被 7,则返回(by7)等等...... . 这是我的代码:

(defun checknum(n)
    let* (resultt '() ) ( 
      if(not(and(plusp n ) (integerp n))) (cons nil resultt) (progn 
                       (if (zerop (mod n 7)) (cons 'by7 resultt) (cons nil resultt))
                       (if (zerop (mod n 5)) (cons 'by5 resultt) (cons nil resultt)) 
                       (if (zerop (mod n 3))  (cons 'by3 resultt) (cons nil resultt) )) ))

但是如果我为 ex 发送 21,我只会得到 nil,而不是 (by3by7) 我猜局部变量不受我的 if 语句的影响,我不知道该怎么做......

最佳答案

(cons x y) 创建一个新的 cons 单元并处理结果。要更改变量的值,您需要使用 setqsetfpush 等,例如:

(defun checknum (n)
  (let ((resultt nil))
    (when (and (plusp n) (integerp n))
      (when (zerop (mod n 7)) (push 'by7 resultt))
      (when (zerop (mod n 5)) (push 'by5 resultt))
      (when (zerop (mod n 3)) (push 'by3 resultt)))
    resultt))

或者更优雅地使用内部函数来排除重复:

(defun checknum (n)
  (when (and (plusp n) (integerp n))
    (labels ((sub (d nsym res)
               (if (zerop (mod n d))
               (cons nsym res)
               res)))
      (sub 7 'by7
       (sub 5 'by5
        (sub 3 'by3 nil)))))

测试:

CL-USER> (checknum 12)
(BY3)
CL-USER> (checknum 15)
(BY3 BY5)
CL-USER> (checknum 105)
(BY3 BY5 BY7)
CL-USER> (checknum 21)
(BY3 BY7)

关于function - Lisp-在函数的多个语句中修改局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35978098/

相关文章:

php - 如何在 SQL 语句中使用 PHP 变量

java - 在 Java 中模拟 if-in 语句

php - 搜索目录,仅搜索 jpg/js 并在数组中获取

python - 将默认值与参数名称匹配

使用函数和字符数组计算字符串长度的C程序

javascript - jquery 解决方案/javascript 函数分配变量

c - 在memcached中存储指针

c++ - 我应该专攻还是重载?

java - 数组 If 语句问题

c# - 如果条件在 linq