这个Lisp代码如何工作?

时间:2012-10-09 08:34:27

标签: lisp common-lisp

此功能检查列表中的数字。例如,它在这里寻找12.如果有12,则返回T(真),如果不存在,则返回NIL。我试图理解语法,但它让我感到困惑。是否有人可以用简单的英语帮助并描述这段代码的用途?

1> (defun an (&rest n)
    (block nil
      (setq x (car n))
      (setq n (cdr n))
      (loop (< x 100)
      (setq n (cdr n))
      (if (eq x 2) (return (eq (car n) 12))) (setq x (1- x)))))
AN
2> (an 2 3 4 5 66 7)
NIL
3> (an 2 3 12 3 4 5)
T

其他问题:&rest如何运作或做什么?

1 个答案:

答案 0 :(得分:1)

如果您正在使用SLIME,那么当该点位于块形式的最后一个括号时,您可以执行 M-x slime-macroexpand-all。你会得到这样的东西:

(BLOCK NIL
  (SETQ X (CAR N))                      ; save the first element in X, while declaring
                                        ; a special variable by that name
  (SETQ N (CDR N))                      ; set N to the second cons of the list
  (BLOCK NIL
    (TAGBODY
     #:G892
      (PROGN
       (< X 100)                        ; Useless, has no impact on your code
       (SETQ N (CDR N))                 ; set N to the third cons of the list
       (IF (EQ X 2)
           (RETURN-FROM NIL (EQ (CAR N) 12))) ; return from the innermost block NIL
                                        ; however, since there's no more code in the
                                        ; outermost block NIL, this will return from
                                        ; it too.
       (SETQ X (1- X)))                 ; decrement value in X. It may happen so by
                                        ; chance that, if initially X was larger than 2
                                        ; the above condition will trigger
      (GO #:G892))))

也许,如果你解释了你想要做什么,你会得到更好的运气,这个功能是错误的,它正在乞求这个问题。