Open In App

Loops in LISP

Loops allow executing a set of instructions repeatedly while some condition is true. LISP provides the following types of loops:

1. dotimes loop:

The dotimes loop allows executing instructions for a fixed number of times.
Syntax: 



(dotimes( variableName numberOfIterations ) (
  expressions 
))

Where,

Example:






(dotimes (a 4)
  (print a))
(write-line "")

Output:

You can also return from the loop if a certain condition is met




(dotimes (i 7)
   (if (> i 5)
       (return)
       (print i))
    )
(write-line "")

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:

2.  loop:

The loop construct allows executing some statement(s) repeatedly until it finds a return statement.

Syntax: 

( loop   
  (expressions)
  ( when (condition) (return returnValue))
)

Where,

Example:




(defvar n 3)
(loop
    (print n)
    (setq n (+ n 1))
    (when (> n 6) (return n))
)
(write-line "")

Here, n is printed and incremented until it becomes greater than 6.
Output:

3. loop for:

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:




; initialize x=12, execute instructions, 
; increment it by 3 and perform iteration until it is less than 25
(loop for x from 12 to 25 by 3 do
    (print x)
)
(write-line "")

Output:

4. do:

The 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:




(do ((a 0 (+ 2 a))
   (b 20 ( - b 2)))
   ((= a b)(- a b))
   (format t "~% a = ~d  b = ~d" a b)
)
(write-line "")

Output:

5. dolist:

The dolist construct provides an easy way to traverse lists.

Syntax:

(dolist (listItemVariable list)
   (expressions)
) 

Where,

Example:




(defvar nums `(9 5 2 3))
(dolist (item nums)
  (print item)
)
(write-line "")

Output:

References:


Article Tags :