Lisp - loop construct



The loop construct is the simplest form of iteration provided by LISP. In its simplest form It allows you to execute some statement(s) repeatedly until it finds a return statement.

It has the following syntax −

(loop (s-expressions))

Example

Create a new source code file named main.lisp and type the following code in it.

main.lisp

; set a as 10
(setq a 10)
; start a loop
(loop 
   ; increment a by 1
   (setq a (+ a 1))
   ; print a
   (write a)
   ; terminate printing
   (terpri)
   ; return a if a becomes greater than 17
   (when (> a 17) (return a))
)

Output

When you execute the code, it returns the following result −

11
12
13
14
15
16
17
18

Please note that without the return statement, the loop macro would produce an infinite loop.

Example

Update the source code file named main.lisp and type the following code in it. In this example, we're printing numbers in descending order.

main.lisp

; set a as 20
(setq a 20)
; start the loop
(loop 
   ; decrement a by 1
   (setq a (- a 1))
   ; print a
   (write a)
   ; terminate printing
   (terpri)
   ; if a becomes less than 10, return the same.
   (when (< a 10) (return a))
)

Output

When you execute the code, it returns the following result −

19
18
17
16
15
14
13
12
11
10
9
lisp_loops.htm
Advertisements