Lisp - loop for construct
The loop for construct allows you to implement a for-loop like iteration as most common in other languages.
It allows you to
set up variables for iteration
specify expression(s) that will conditionally terminate the iteration
specify expression(s) for performing some job on each iteration
specify expression(s), and expressions for doing some job before exiting the loop
The for loop for construct follows several syntax −
(loop for loop-variable in <a list> do (action) ) (loop for loop-variable from value1 to value2 do (action) )
Example - loop on strings
Create a new source code file named main.lisp and type the following code in it −
main.lisp
; loop on strings and print each value (loop for x in '(tom dick harry) ; print x do (format t " ~s" x) )
Output
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
TOM DICK HARRY
Example - loop on numbers
Update the source code file named main.lisp and type the following code in it −
main.lisp
; loop on each number and print (loop for a from 10 to 20 ; print a do (print a) )
Output
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
10 11 12 13 14 15 16 17 18 19 20
Example - conditional loop on numbers
Update the source code file named main.lisp and type the following code in it −
main.lisp
; loop numbers from 1 to 20 (loop for x from 1 to 20 ; if number is even if(evenp x) ; print x do (print x) )
Output
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
2 4 6 8 10 12 14 16 18 20