Open In App

Loop For Construct in LISP

The loop for construct in common LISP is used to iterate over an iterable, similar to the for loop in other programming languages. It can be used for the following:

  1. This is used to set up variables for iteration.
  2. It can be used for conditionally terminate the iteration.
  3. It can be used for operating on the iterated elements.

The loop For construct can have multiple syntaxes.



Syntaxes:

(loop for variable in input_list
  do (statements/conditions)
)

Here,



  1. input_list is the list that is to be iterated.
  2. The variable is used to keep track of the iteration.
  3. The statements/conditions are used to operate on the iterated elements.
(loop for variable  from number1 to number2
 do (statements/conditions)
)

Here,

Example: LISP Program to print numbers in a range




;range from 1 to 5
(loop for i from 1 to 5
       
;display each number
   do (print i)
)

Output:

1 
2 
3 
4 
5 

Example 2: LISP Program to iterate elements over a list.




;list with 5 numbers
(loop for i in '(1 2 3 4 5)
       
;display each number
   do (print i)
)
 
;list with 5 strings
(loop for i in '(JAVA PHP SQL HTML CSS)
       
;display each string
   do (print i)
)

Output:

1 
2 
3 
4 
5 
JAVA 
PHP 
SQL 
HTML 
CSS 

Example 3: LISP Program to iterate each number from range and perform increment and decrement operations.




;list with 5 numbers
(loop for i in '(1 2 3 4 5)
 
;display each number by incrementing each number by 5
   do (print (incf i 5))
)
 
;list with 5 numbers
(loop for i in '(1 2 3 4 5)
 
;display each number by decrementing each number by 5
   do (print (decf i 5))
)

Output:

6 
7 
8 
9 
10 
-4 
-3 
-2 
-1 
0 

Article Tags :