Open In App

Loop For Construct in LISP

Last Updated : 04 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • To iterate over a list:
(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.
  • To iterate over the given range:
(loop for variable  from number1 to number2
 do (statements/conditions)
)

Here,

  • The number1 is the starting number and number 2 is the ending number from the range.
  • The variable is used to keep track of the iteration.
  • The statements/conditions are used to operate on the iterated elements.

Example: LISP Program to print numbers in a range

Lisp




;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.

Lisp




;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.

Lisp




;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 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads