Lisp - Cond Construct



The cond construct in LISP is most commonly used to permit branching.

Syntax for cond is −

(cond   (test1    action1)
   (test2    action2)
   ...
   (testn   actionn))

Each clause within the cond statement consists of a conditional test and an action to be performed.

If the first test following cond, test1, is evaluated to be true, then the related action part, action1, is executed, its value is returned and the rest of the clauses are skipped over.

If test1 evaluates to be nil, then control moves to the second clause without executing action1, and the same process is followed.

If none of the test conditions are evaluated to be true, then the cond statement returns nil.

Example

Create the source code file named main.lisp and type the following code in it. Here we're using cond construct with failed condition.

main.lisp

; set a as 10
(setq a 10)
; check a being greater than 20
(cond ((> a 20)
   (format t "~% a is greater than 20"))  ; statement is not printed as case is not true
   (t (format t "~% value of a is ~d " a))) ; otherwise print the statement

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

value of a is 10

Please note that the t in the second clause ensures that the last action is performed if none other would.

Example

Update the source code file named main.lisp and type the following code in it. Here we're using cond construct with success condition.

main.lisp

; set a as 30
(setq a 30)
; check a being greater than 20
(cond ((> a 20)
   (format t "~% a is greater than 20")) ;  statement is printed as case is true
   (t (format t "~% value of a is ~d " a))) ; statement is not printed

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

a is greater than 20

Example

Update the source code file named main.lisp and type the following code in it. Here we're using cond construct with not condition.

main.lisp

; set a as 30
(setq a 30)
; check not a as false
(cond ((not a)
   (format t "~% a " a)) ; statement is not printed
   (t (format t "~% NOT a is Nil ~d" a))) ; 

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

NOT a is Nil 30
lisp_decisions.htm
Advertisements