LISP - If Construct



The if macro is followed by a test clause that evaluates to t or nil. If the test clause is evaluated to the t, then the action following the test clause is executed. If it is nil, then the next clause is evaluated.

Syntax for if −

(if (test-clause) (action1) (action2))

Example 1

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

(setq a 10)
(if (> a 20)
   (format t "~% a is less than 20"))
(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

Example 2

The if clause can be followed by an optional then clause.

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

(setq a 10)
(if (> a 20)
   then (format t "~% a is less than 20"))
(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 −

a is less than 20
value of a is 10 

Example 3

You can also create an if-then-else type statement using the if clause.

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

(setq a 100)
(if (> a 20)
   (format t "~% a is greater than 20") 
   (format t "~% a is less than 20"))
(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 −

a is greater than 20
value of a is 100  
lisp_decisions.htm
Advertisements