![]() |
VOOZH | about |
Loops allow executing a set of instructions repeatedly while some condition is true. LISP provides the following types of loops:
The dotimes loop allows executing instructions for a fixed number of times.
Syntax:
(dotimes( variableName numberOfIterations ) ( expressions ))
Where,
Example:
Output:
👁 ImageYou can also return from the loop if a certain condition is met
Here, the loop is set to iterate 7 times, however, when the value becomes more than 5, the loop stops because the condition is met.
Output:
The loop construct allows executing some statement(s) repeatedly until it finds a return statement.
Syntax:
( loop (expressions) ( when (condition) (return returnValue)) )
Where,
Example:
Here, n is printed and incremented until it becomes greater than 6.
Output:
The loop for construct is similar to the for-loops in popular languages like java, c++, etc. It can also be used to traverse lists and other data structures.
Syntax:
( loop for variableName from startValue to endValue by changeValue do (expressions) )
Where,
Example:
Output:
👁 ImageThe do construct allows a structured form of iteration.
Syntax:
(do ((variable_1 value_1 updated-value_1) (variable_2 value_2 updated-value_2) (variable_3 value_3 updated-value_3) ...) (test return_value) (s-expressions) )
Where,
The initial values of each variable are evaluated and bound to the respective variable. The updated value in every clause is with respect to an optional update statement which indicates how to update variables in each iteration.
The test is performed on each iteration and if the test expression results in a non-null or true value, the returned value is evaluated and returned.
If the last optional s-expression(s) are specified, they're executed on every iteration while test expression results are true.
Example:
Output:
👁 ImageThe dolist construct provides an easy way to traverse lists.
Syntax:
(dolist (listItemVariable list) (expressions) )
Where,
Example:
Output:
👁 ImageReferences: