Loop Construct in LISP

In this article, we will discuss Loop Construct. This Construct is used to iterate the data until it finds the return statement. And then it will stop iterating and return the results.

Syntax:

(loop (statements)
condition
return 
)

where,

  • loop is the keyword
  • statements are used to iterate the loop
  • condition is used to specify the condition so that the loop stops iterating
  • return statement is used to return the results

Example: LISP Program to iterate over elements

Lisp




;define a variable and set to 1
(setq var 1)
  
;start the loop
(loop 
   
;increment value by 2 each time
;till value is less than 30
   (setq var (+ var 2))
   
   ;display
   (write var)
   (terpri)
   
   ;condition for value is less than 30
   (when (> var 30) (return var))
)


Output:

3
5
7
9
11
13
15
17
19
21
23
25
27
29
31

Example 2:

Lisp




;define a variable and set to 100
(setq var 100)
  
;start the loop
(loop 
   
;decrement value by 10 each time
;till value is less than 30
   (setq var (- var 10))
   ;display
   
   (write var)
   (terpri)
   
   ;condition for value is less than 30
   (when (< var 30) (return var))
)


Output:

90
80
70
60
50
40
30
20


Contact Us