Iteration & Block Structure

June 8, 2008 | Filed Under Common Lisp - Touretzky 

———————————————————
Chapter 11
———————————————————

Iteration and Block Structure

(dotimes (i 4)
(format t “~&I is ~S.” i))
I is 0.
I is 1…

(dolist (x ‘(red green blue) ‘flowers)
(format t “~&Roses are ~S” x))
Roses are RED
Roses are BLUE
Roses are GREEN
FLOWERS

dolist returns the final symbol in its parameters (i.e. Flowers, above)

RETURN can be used to break the loop - returns the value of its argument:

(defun find-odd (num-list)
(dolist (x num-list NIL)
(if (oddp x) x)))

Can set a symbol to hold the result of an operation and pass back:

(defun it-intersection (x y)
(let ((result-set NIL))
(dolist (element x result-set)
(when (member element y)
(push element result-set)))))
-> result-set gets passed back as final element of dolist.

The DO macro:

takes the form (DO ( (var1 initial [update])
(var2 initial [update]))
(test action1… actionN)
body)

return the final action

i.e. (defun count-down ()
(do ((cnt 10 (- cnt 1))
((zerop cnt) (format t “GO!”)
(format t “~S…” cnt)))

need not have a body - all work can be done in the loop and then output as the last action in the test function.

the [update] function need not just be an increment/decrement:
(defun test-fn (x)
(do ((var1 x (rest x)))…

Looping through one list is best done with DOLIST, but can loop through 2 simultaneously with DO:

(defun find-matching-elements (x y)
(do ((x1 x (rest x1))(y1 y (rest y1)))
((or (null x1) (null y1)) nil)
(if (equal (first x1) (first y1))
(retun (first x1)))))

DO* allows sequential setting of variables, like LET*

(defun find-first-odd (number-list)
(do* ((x number-list (rest x))
(e (first x) (first x))
((null x) NIL)
(if (oddp e) (return e))))

Comments

One Response to “Iteration & Block Structure”

  1. Philip Werner on June 25th, 2008 12:38 pm

    Surprised to see Lisp on your site. I took a Lisp class from Dave Touretsky at CMU using a draft of his book in 1982 at CMU as an undergrad. After that programmed in it for 13 years. It is a beautiful thing. Why are you learning this?

Leave a Reply