Lisp Books

Tuesday 23 March 2010

Predicates In Lisp

Today we're looking at predicates. Predicates are tests that we can use to see if something is true or false.

Before we do that let's look at the answers from yesterday:

(defun minus-one (x)
   (- x 1))

(defun ten-times-bigger (x)
   (* x 10))

(defun weeks-to-days (weeks)
   (* weeks 7))

It doesn't matter if you called weeks x or something entirely different, it is often useful to give our arguments names that are useful.

Predicates
As mentioned earlier predicates are tests that return either True or False. In lisp:

T = True
Nil = False

Here are some examples:

oddp checks to see if a number is odd:

(oddp 5)
T

(oddp 6)
NIL

evenp checks to see if a number is even:

(evenp 5)
NIL

(evenp 6)
T

Here are some other common predicates with examples:
(zerop 0)
T

(= 3 4)
NIL

(> 3 4)
NIL

(< 5 10)
T



Predicate Summary
  • (evenp n) true if n is even
  • (floatp n) true if n is a floating point number
  • (integerp n) true if n is an integer
  • (minusp n) true if n is less than zero
  • (numberp n) true if n is a number 
  • (oddp n) true if n is an odd number (0 is considered even) 
  • (plusp n) true if n is greater than 0 
  • (zerop n) true if n is 0
  • (> x y) true if x is greater than y
  • (< x y) true if x is less than y
  • (>= x y) true if x is greater than or equal to y
  • (<= x y) true if x is less than or equal to y
Using Predicates In Functions
In yesterday's post we wrote our own functions. We can include predicates in these functions. For example, this function adds two numbers together and checks to see if the result is even, again we could all it almost anything but as it's a predicate that check to see if the sum of two numbers is even we'll call it sum-even-p:

(defun sum-even-p (x y)
   (evenp (+ x y)))



Notice the order of the function

    (evenp (+ x y)))

the input element to evenp is the + function and x y


Today's Challenge
Today's challenge write a function called square-odd-p. This function takes a single number as input, it squares this number and tests to see if the square of the number is odd.

Check tomorrow's post for the answer and more Lisp tutorials.