Conditional Expressions
Abelson and Sussman introduce some dynamism into their procedures by using conditional statements. The procedures in the previous sections were simple and were unidimensional because they would only express what was initially given by the program. By incorporating conditional statements, the procedures can now respond to outcomes according to a set of rules. Conditions are set primarily with predicates, which are statements that return or evaluate to true or false. If the predicate returns true, the consequent expression is executed, while if the predicate returns false, an alternative is executed or the procedure is undefined. This simple fork in the road is a fundamental building block that will harness the infinite decisions that will be made.
Here are some examples:
We can use a simple if-then-else expression in the following way, which is codified in Lisp as if-predicate-consequent expression. We write a function that states if X is greater than 0, i.e., a positive integer, then add 5. Otherwise, simply return x.
[1]> (defun add5 (x)
(if (> x 0)
(+ x 5)
x))
ADD5
[2]> (add5 6)
11
[3]> (add5 -6)
-6
If there are multiple conditions to be tested, one can use cond
. The example adds or subtracts depending on X being a positive or negative integer:
[1]> (defun addsub1 (x)
(cond ((> x 0) (+ x 1))
((< x 0) (- x 1))
(x))
)
ADDSUB1
[2]> (addsub1 2)
3
[3]> (addsub1 -2)
-3
[4]> (addsub1 0)
0