0

I have a little problem to understand do in lisp

I have this code :

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

In documentation there is the "do" basic template is:

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

I really don't understand where is my body in my function iota-b For me it's

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

apparently not, why we put (u '() (cons x u))) in the variable-definitions ?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
mpgn
  • 7,121
  • 9
  • 67
  • 100
  • Correct indenting would have hinted at the problem. I suggest not editing the post with respect to that, because the original indentation makes it clear, where the question may stem from. – Philipp Matthias Schäfer Dec 13 '13 at 08:15
  • 1
    Is it more Lispy to wrestle with parentheses than to give in to the Devil and do `(loop for x to 3 collect x)`? – Kaz Dec 14 '13 at 01:23

2 Answers2

6

You have the variable definitions of the form var init [step]

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

this increments x in every iteration and builds with (cons x u) the u list as (5 4 3 2 1 0).

The end test

(> x n)

The result form

(nreverse u)

reverses the list (5 4 3 2 1 0) to the given result.

And then you have an empty body.

You can of course modify the do loop to

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

this will give the same result.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
3
(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

    ))
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346