理解Common Lisp做宏语法

时间:2012-04-17 05:56:19

标签: lisp iteration common-lisp

(do ((n 0 (1+ n))
     (cur 0 next)
     (next 1 (+ cur next)))
    ((= 10 n) cur)))

这是Lisp教科书中关于关键字“do”

的一个例子

“do”基本模板是:

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

但是,对于这个例子,我不清楚哪个部分是哪个部分。而且,中间2行是做什么的?

谢谢!

4 个答案:

答案 0 :(得分:24)

(do ((n 0 (1+ n))  ;declares n, initially 0, n+1 each subsequent iteration)
     (cur 0 next)   ;declares cur, initially 0, then old value of next
     (next 1 (+ cur next))) ;declares next, initially 1, then the sum of (the old) cur and next
    ((= 10 n) ;end condition (ends when n = 10)
     cur)    ; return value
  ;empty body
  )

转换为类似c的代码

for(n=0, cur=0, next=1 ;
    !(n == 10) ;
    n=old_n+1, cur=old_next, next = old_cur + old_next)
{
    //do nothing 
    old_n = n;
    old_cur = cur;
    old_next = next;
}
return cur;

顺便说一下,您应该能够看到此代码返回第10个Fibonacci数


可选的EBNF /形式语法:

根据Hyperspec的语法是:

(do ({var | (var [init-form [step-form]])}*) 
    (end-test-form result-form*) 
    declaration* 
    {tag | statement}*)

理解这一点需要了解EBNF和Hyperspec的大块

答案 1 :(得分:10)

你的良好缩进清楚地表明哪一部分是:

(do ((n 0 (1+ n))
    ^(cur 0 next)
    |(next 1 (+ cur next)))
    |
    +-- first argument of do

    ((= 10 n) cur)))
    ^
    |
    +-- start of second argument of do

看,它们很好地对齐,内部材料是缩进的:

   ((n 0 (1+ n))
    (cur 0 next)
    (next 1 (+ cur next)))
    ^
    |
    +- inner material of argument: three forms which are
       indented by 1 character and aligned together.

你的do在那里没有第三个参数:没有语句体(空循环)。

答案 2 :(得分:0)

(do ((n 0 (1+ n))
     (cur 0 next)
     (next 1 (+ cur next)))
    ((= 10 n) cur))

有3部分。

  1. 可变
  2. 终止条件
  3. 在这个特定的例子中,没有身体。所有实际工作由1.和2.完成它首先设置3个变量并给出初始值和步骤形式。例如。 n设置为0,并且在每次迭代过程中它都会进一步:(1+ n)这会增加n

    终止条件为((= n 10) cur):当n等于10.然后返回cur作为此do表达式的整个返回值。

    结合所有这些,在这个do示例中,它将从1到10总和,产生55

答案 3 :(得分:0)

有时候,这可能有助于1.用注释对表单进行注释,以及2.在正文中打印当前值,如下所示:

(do
 ;; varlist
 ((n 0 (1+ n))
  (cur 0 next)
  (next 1 (+ cur next)))
 ;; endlist
 ((= 10 n) cur)
  ;; body
  (print (list n cur next)))

此打印

(0 0 1) 
(1 1 1) 
(2 1 2) 
(3 2 3) 
(4 3 5) 
(5 5 8) 
(6 8 13) 
(7 13 21) 
(8 21 34) 
(9 34 55) 
55

这应该解决问题。 @ _ @

相关问题