Open In App

Do Construct in LISP

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss the Do Construct in LISP. Do construct is used to perform an iteration in a structured format.

Syntax:

(do ((variable1    value1   new updated value 1)
    (variable2   value2   new updated value 2)
-------------------------------
-------------------------------
    (variable n   value n    new updated value n)
 ...)
 (test statements)  
)

Here,

  1. variables are the input values.
  2. new updated values are the values that are updated based on the condition given in the value.
  3. test statements are to be executed at the final.

Example 1: LISP Program to get value increment and decrement display until the given condition

Lisp




;define value 1 to 0
;define value 2 to 30
(do ((val1 0 (+ 2 val1))
   (val2 24 ( - val2 2)))
    ;display both values until value1 is equal to  value2
    ;by incrementing value1 by 2
    ;by decrementing value2 by 2
   ((= val1 val2)(- val2 val2))
    ;display
   (format t "~% value 1 = ~d  and  value 2  = ~d" val1 val2)
)


Output:

value 1 = 0  and  value 2  = 24
value 1 = 2  and  value 2  = 22
value 1 = 4  and  value 2  = 20
value 1 = 6  and  value 2  = 18
value 1 = 8  and  value 2  = 16
value 1 = 10  and  value 2  = 14

Example 2: LISP Program to display all till value 1 is greater than value 2 by performing increment and decrement operations

Lisp




;define value 1 to 0
;define value 2 to 30
(do ((val1 0 (+ 2 val1))
   (val2 24 ( - val2 2)))
    
    ;display both values until value1 is greater than  value2
    ;by incrementing value1 by 2
    ;by decrementing value2 by 2
   ((> val1 val2)(- val2 val2))
    ;display
   (format t "~% value 1 = ~d  and  value 2  = ~d" val1 val2)
)


Output:

value 1 = 0  and  value 2  = 24
value 1 = 2  and  value 2  = 22
value 1 = 4  and  value 2  = 20
value 1 = 6  and  value 2  = 18
value 1 = 8  and  value 2  = 16
value 1 = 10  and  value 2  = 14
value 1 = 12  and  value 2  = 12


Last Updated : 09 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads