Search code examples
lispiterationcommon-lisp

Understanding Common Lisp do macro syntax


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

This is an example from a Lisp textbook about the keyword do.

The do basic template is:

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

But, for this example, it's not clear to me which part is which. And also, what do the middle 2 lines do?


Solution

  • Your good indentation clearly shows which part is which:

    (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
    

    Look, they line up nicely, and the inner material is indented:

       ((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.
    

    Your do doesn't have a third argument there: there is no body of statements (empty loop).