Lisp - case Construct



The case construct implements multiple test-action clauses like the cond construct. However, it evaluates a key form and allows multiple action clauses based on the evaluation of that key form.

The syntax for case macro is −

The template for CASE is

(case  (keyform)
((key1)   (action1   action2 ...) )
((key2)   (action1   action2 ...) )
...
((keyn)   (action1   action2 ...) ))

Example

Create a new source code file named main.lisp and type the following code in it.

main.lisp

; set day as 4
(setq day 4)
; compare day with corresponding cases and print the respective day
(case day
   (1 (format t "~% Monday"))
   (2 (format t "~% Tuesday"))
   (3 (format t "~% Wednesday"))
   (4 (format t "~% Thursday"))
   (5 (format t "~% Friday"))
   (6 (format t "~% Saturday"))
   (7 (format t "~% Sunday")))

Output

When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −

Thursday

Example

Update the source code file named main.lisp and type the following code in it. In this example, we're performing different operations based on cases.

main.lisp

; set a as 2
(setq a 2)
; set b as 3
(setq b 3)
; set c as 3 to represent a case for multiplication
(setq c 3)

; compare c with corresponding cases and print the respective operation result
(case c
   (1 (print (+ a b)))  ; get sum
   (2 (print (- a b)))  ; get substraction
   (3 (print (* a b)))  ; get multiplication 
   (4 (print (/ a b))))  ; get division

Output

When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −

6
lisp_decisions.htm
Advertisements