Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

(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

    ))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top