2014-02-17 43 views
0

我有这个列表代码块。LISP做功能行为?

(defun test (y) 
    (do 
     ((l NIL (setq y (rest y)))) 
     ((null y) 1) 
     (setq l (append l '(1 1))) 
     (print l) 
    ) 
) 

输出结果如下图所示。出于某种原因,它将l设置为y,然后追加'(1 1)。谁能解释这种行为?

enter image description here

回答

3

一个do环的结构是:

(do ((var init-form step-form)) 
    (termination-form result-form) 
    (body)) 

我认为你缺少的是step-form在每次迭代执行和结果这种形式的设为变量。因此在step-form中使用setq是一个标志,您可能没有按照您的意图进行操作。

所以循环从(test '(2 3 4))的序列(eliding打印)

- Initialize l to nil 
- Check (null y) which is false since y = '(2 3 4). 
- (setq l (append l '(1 1))) l now has the value '(1 1) 
- Execute the step form, this sets y = '(3 4) _and_ l = '(3 4) 
- (null y) still false. 
- (setq l (append l '(1 1))) sets l = '(3 4 1 1) 
- Execute step form, sets y = '(4) _and_ l = '(4) 
- (setq l (append l '(1 1))) sets l = '(4 1 1) 
- Execute step form, y =() so loop terminates. 
+0

啊感谢解释得这么好!绝对清除了我的困惑。 – Coat