【问题标题】:How does this Lisp code work? [closed]这个 Lisp 代码是如何工作的? [关闭]
【发布时间】:2012-09-29 13:03:34
【问题描述】:

下面的这个函数检查列表中的数字。例如,这里它正在寻找 12。如果 12 存在,则返回 T (true),如果不存在,则返回 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

附加问题:&amp;rest 是如何工作的或者它有什么作用?

【问题讨论】:

    标签: lisp common-lisp


    【解决方案1】:

    如果您使用的是 SLIME,您可以在该点位于块形式的最后一个括号上时执行 M-xslime-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))))
    

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

    【讨论】:

    • 感谢该函数应该在列表中找到一个元素或原子,在这种情况下为 12(1 2 3 4 5 6 12),如果它存在,则函数应该返回 true,否则它应该返回无
    猜你喜欢
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 2010-12-13
    • 2013-04-23
    • 2015-04-09
    • 2013-07-24
    • 2014-03-26
    • 2012-11-14
    相关资源
    最近更新 更多