【问题标题】:Understanding Common Lisp do syntax理解 Common Lisp 的 do 语法
【发布时间】:2013-12-12 22:14:17
【问题描述】:

在 lisp 中我有一个小问题要理解

我有这个代码:

(defun iota-b (n)
  (do ((x 0 (+1 x))
      (u '() (cons x u)))
      ((> x n) (nreverse u))))

(iota-b 5)

(0 1 2 3 4 5)

在文档中有“do”的基本模板是:

(do (variable-definitions*)
    (end-test-form result-form*)
 statement*)

我真的不明白我的身体在我的函数 iota-b 中的什么位置 对我来说是

(u '() (cons x u)))

显然不是,为什么我们将 (u '() (cons x u))) 放在变量定义中?

【问题讨论】:

  • 正确的缩进会暗示这个问题。我建议不要对此进行编辑,因为原始缩进清楚地表明了问题的根源。
  • 与括号搏斗比向魔鬼屈服并做(loop for x to 3 collect x)更Lispy吗?

标签: syntax lisp common-lisp do-loops


【解决方案1】:

你有var init [step]形式的变量定义

((x 0 (+1 x))
 (u '() (cons x u)))

这会在每次迭代中递增x,并使用(cons x u) 构建u 列表为(5 4 3 2 1 0)

结束测试

(> x n)

结果形式

(nreverse u)

将列表 (5 4 3 2 1 0) 反转为给定的结果。

然后你有一个空的身体。

你当然可以将do循环修改为

(do ((x 0 (+1 x))
     (u '()))
    ((> x n) (nreverse u))
  (setq u (cons x u)))

这将给出相同的结果。

【讨论】:

  • @Martialp 您问题中的代码没有正确缩进。你明白修复缩进后发生了什么吗(在任何好的编辑器中点击Tab)?
  • 是的,我看到了!嗯,谢谢,我想我明白了,谢谢!
【解决方案2】:
(defun iota-b (n)
  (do 
      ; var init step
      ((x   0    (1+ x))       ; var 1
       (u   '()  (cons x u)))  ; var 2

      ;test    result
      ((> x n) (nreverse u))   ; end ?

    ; body comes here
    ; this DO loop example has no body code
    ; the body code is optional

    ))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多