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 a new source code file named main.lisp and type the following code in it −

(setq a 10)
(cond ((> a 20)
   (format t "~% a is greater than 20"))
   (t (format t "~% value of a is ~d " a)))

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.

lisp_decisions.htm
Advertisements