EXAMPLES OF LOOPS IN LISP
Also Prog1 and Progn
Chapter 7 Winston/Horn Lisp
1. DOTIMES (dotimes (count-parameter upper-bound result)
body...)
(defun do-times-expt (base exp)
(let ((result 1))
(dotimes (count n result) ;;loop n times
(setf result (* base result)))))
2. DOLIST (dolist (element list result)
body...)
(setf freezing 32 boiling 212)
(defun count-outlyers (list-of-elements)
(let ((result 0))
(dolist (element list-of-elements result)
(when (or (> element boiling)
(< element freezing))
(setf result (+ result 1))))))
3. DO A general loop
(defun do-expt (base exp)
(do ((result 1)
(exponent exp))
((zerop exponent) result) ;;test to exit loop
(setf result (* base result)) ;;Body of loop
(setf exponent (- exponent 1)))))
4. LOOP Loop until return
(setf cheers 'cheers '(cheer cheer cheer))
(setf loop-count 0)
(loop
(when (endp cheers) (return loop-count))
(setf cheers (rest cheers))
(setf loop-count (+ loop-count 1)))
5. PROG1 and PROGN Grouping statements
(prog1 (setf a 'x) (setf b 'y) (setf c 'z))
X
(progn (setf a 'x) (setf b 'y) (setf c 'z))
Z