Lisp - dolist construct
The dolist construct allows iteration of each element of a list.
Syntax
(dolist (n list) statement1 ... )
n − item of list.
list − list to be iterated.
statement1 − statement(s) to be evaluated.
Example - Print all elements of a list
For example, Create a new source code file named main.lisp and type the following code in it −
main.lisp
; perform a dolist operation on list of numbers (dolist (n '(1 2 3 4 5)) (print n) ; print the number )
Output
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
1 2 3 4 5
Example - Qube of Numbers
Update the source code file named main.lisp and type the following code in it −
main.lisp
; perform a dolist operation on list of numbers (dolist (n '(1 2 3 4 5)) (print n) (prin1 (* n(* n n))) ; print the qube of number )
Output
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
1 1 2 8 3 27 4 64 5 125
Example - Double of a Number
Update the source code file named main.lisp and type the following code in it −
main.lisp
; perform a dolist operation on list of numbers (dolist (n '(1 2 3 4 5)) (print n) (prin1 (+ n n)) ; print double of number )
Output
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
1 2 2 4 3 6 4 8 5 10
lisp_loops.htm
Advertisements