Iteration and Block Structure

DOTIMESAND DOLIST

(DOTIMES (index-var n [result-form]) body)

> (dotimes (i 4)
(format t "~&I is ~S." i))

(DOLIST (index-var list [result-form]) body)

> (dolist (x ’(red blue green) ’flowers)
(format t "~&Roses are ~S." x))

EXITINGTHE BODY OF A LOOP

(defun check-all-odd (list-of-numbers)
(dolist (e list-of-numbers t)
(format t "~&Checking ~S..." e)
(if (not (oddp e)) (return nil))))
> (check-all-odd ’(1 3 5))
Checking 1...
Checking 3...
Checking 5...
T
> (check-all-odd ’(1 3 4 5))
Checking 1...
Checking 3...
Checking 4...
NIL

For searching a flat list, iteration is simpler to use than recursion

DOTIMES

(defun it-fact (n)
(let ((prod 1))
(dotimes (i n prod)
(setf prod (* prod (+ i 1))))))
(it-fact 5) ⇒ 120

missing part

Lisp Toolkit: TIME

(defun addup (n)
"Adds up the first N integers"
(do ((i 0 (+ i 1))
(sum 0 (+ sum i)))
((> i n) sum)))
> (time (addup 1000)) Input is one thousand.
Evaluation took:
0.83 seconds of real time,
0.65625 seconds of user run time,
81 page faults, and
48208 bytes consed.
500500

missing part