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

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

main.lisp

; set a as 10
(setq a 10)

; check if a is greater than 20
(if (> a 20)
   ; print the result if a is less than 20
   (format t "~% a is less than 20"))
; print the value of a   
(format t "~% value of a is ~d " a)

Output

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

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.

main.lisp

; set a as 10
(setq a 10)
; check if a is greater than 20
(if (> a 20)
   ; print statement if a is greater than 20
   then (format t "~% a is less than 20"))
; print value of a   
(format t "~% value of a is ~d " a)

Output

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

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.

main.lisp

; set a as 100
(setq a 100)
; if a is greater than 20
(if (> a 20)
   ; print statement if a is greater than 20
   (format t "~% a is greater than 20") 
   ; else print this statement
   (format t "~% a is less than 20"))
(format t "~% value of a is ~d " a)

Output

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