我是 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 单元并处理结果。要更改变量的值,您需要使用 setq
、setf
、push
等,例如:
(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/