Music 220b: Winter 2001
Fernando Lopez-Lezcano, instructor
Christopher Burns, teaching assistant
Tamara Smyth, teaching assistant
Week 2: the loop macro
Here are a number of examples of the loop macro; hopefully they explain themselves....
Note that the (format) function is a way of generating printed output. There are far too many flags, parameters and tricks to describe here -- suffice it to say that format prints whatever appears between the double quotation marks, and that the "~d"s are placeholders for variables, which then get filled in by i, j, etc.
Each of these (loop) calls returns NIL in addition to calling (format) -- this is a result of the convention that every lisp function returns a value. In cases where we don't want a function to return a value, we can safely ignore the NIL.
Finally, remember that every loop needs to have a termination condition: otherwise it will go on forever.... Loops may have more than one termination condition -- in which case the loop will terminate whenever any of the conditions are met.
CM(33): (loop for i from 0 below 4 do (format t "~d " i)) 0 1 2 3 NIL
CM(34): (loop for i from 0 below 4 for j from 10 do (format t "~d ~d " i j)) 0 10 1 11 2 12 3 13 NIL
CM(35): (loop for i from 0 below 4 for j from 10 by 3 do (format t "~d ~d " i j)) 0 10 1 13 2 16 3 19 NIL
CM(36): (loop for i from 0 downto -4 do (format t "~d " i)) 0 -1 -2 -3 -4 NIL
CM(3): (loop for i from 0 to 4 repeat 2 do (format t "~d " i)) 0 1 NIL
CM(4): (loop for freq = (+ 220 (random 50)) repeat 5 do (format t "~d " freq)) 234 229 236 233 267 NIL
CM(5): (loop for i from 20 by 15 below 70 for freq = (+ 220 i (random 20)) do (format t "~d " freq)) 258 261 282 289 NIL
CM(6): (loop for i from 20 by 15 for freq = (+ 220 i (random 20)) until (> freq 300) do (format t "~d " freq)) 259 260 285 NIL
CM(7): (loop for i from 20 by 15 for freq = (+ 220 i (random 20)) until (> freq 300) do (format t "~d " freq)) 256 271 287 288 NIL
CM(8): (loop for i from 20 by 15 for freq = (+ 220 i (random 20)) until (> freq 300) do (format t "~d " freq)) 241 260 286 293 NIL
CM(11): (loop for current-pitch in '(a4 as4 c5 ef6) with freq do (setf freq (pitch current-pitch)) (format t "~d " freq))) 440.00018 466.16397 523.2511 1244.508 NIL
Guy Steele's online Lisp manual has a chapter on loops with more information.