Predicates can form part of an IF THEN statement: if something is true then do something.
The IF function takes three arguments: a test, a true part, and a
For example, using the ODDP function to test if a number is odd and then returning a statement|:
(if (oddp 3) '(the number is odd) '(the number is even))
(THE NUMBER IS ODD)
(if (oddp 4) '(the number is odd) '(the number is even))
(THE NUMBER IS EVEN)
As well as returning simple statements as in the above example, we can also get Lisp to perform further functions is a test is T or nil. This function for example:
- takes a single number (n) as its input argument.
- tests to see if a number is odd using the ODDP function,
- if the number is odd we add 1 to it to make it even,
- if the ODDP test returns NIL we simply return our original odd number.
(defun make-odd (n)
(if (evenp n) ; the test
(+ 1 n) ;the true statement
n)) ; the false statement
Write a function in Lisp called MY-ABSOLUTE that returns the absolute value of a number. Absolute values are always non-negative. For negative numbers the absolute value multiply the number by -1; for zero and positive numbers the absolute value is the number itself.
Remember the IF function takes three arguments:
- a test
- a true part, and a
- false part