Open In App

Case Construct in LISP

Last Updated : 24 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss the case construct in LISP. This is used to check multiple test conditions at a time, unlike cond, if and when it allows multiple conditions.

Syntax:

(case  (key_value)
((key1)   (statement 1 .............. statement n) )
((key2)   (statement 1 .............. statement n) )
................
((keyn)   (statement 1 .............. statement n) )

Here,

  • key_value is the numeric value taken an input
  • keys are the different conditions to test particular condition specified  in keys

Example 1: LISP Program to get the particular number when the number is given.

Lisp




;define value to 2
(setq val1 2)
 
;define 5 cases from 1 to 5
(case val1
(1 (format t "you selected number 1"))
(2 (format t "you selected number 2"))
(3 (format t "you selected number 3"))
(4 (format t "you selected number 4"))
(5 (format t "you selected number 5"))
)


Output:

you selected number 2

Example 2: LISP Program to perform an arithmetic operation when a particular key is chosen.

Lisp




;define value1 to 10
(setq val1 10)
 
;define value2 to 20
(setq val2 20)
 
;set input to 1
(setq input 1)
 
;define 4 cases to perform each arithmetic operation
(case input
 
;condition to perform addition
(1 (print (+ val1 val2)))
 
;condition to perform subtraction
(2 (print (- val1 val2)))
 
;condition to perform multiplication
(3 (print (* val1 val2)))
 
;condition to perform division
(4 (print (/ val1 val2)))
)


Output:

30 

Now if we set input to 3:

Lisp




;define value1 to 10
(setq val1 10)
 
;define value2 to 20
(setq val2 20)
 
;set input to 3
(setq input 3)
 
;define 4 cases to perform each arithmetic operation
(case input
 
;condition to perform addition
(1 (print (+ val1 val2)))
 
;condition to perform subtraction
(2 (print (- val1 val2)))
 
;condition to perform multiplication
(3 (print (* val1 val2)))
 
;condition to perform division
(4 (print (/ val1 val2)))
)


Output:

200


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

Similar Reads