Lisp Books

Showing posts with label not and or. Show all posts
Showing posts with label not and or. Show all posts

Sunday, 25 April 2010

Using AND NOT and OR in Lisp

Today's Lisp tutorial looks at using AND NOT and OR in Lisp, but firstly let's have a look at the answer to the challenge set in our last Lisp tutorial Using LET in Lisp:

Write a Lisp function called GUESS, where you try and guess the number thrown by a dice, this will have several parts.This function will randomly choose from 6 possibilities. You call the function with your guess of 1, 2, 3, 4 5 or 6, the function randomly chooses 6 choices and tells you if your guess was right or wrong.

(defun guess (n)
  (let ((dice (+ 1 (random 6))))
    (cond ((equalp dice n )  (list  'you 'guessed 'right 'it 'was dice))
          (t (list 'you 'guessed 'wrong 'it 'was dice)))))

The NOT Predicate in Lisp
We've looked at predicates in Lisp in a previous Lisp tutorial post. Predicates return T or  NIL if the statement is true or false. In Lisp T is true and NIL is false. Using NOT turns T into NIL and NIL into T.

For example using the ZEROP predicate we can test if the number is zero:
(zerop 4)
NIL



(zerop 0)
T


Using NOT we can check to see if a number is not zero:
(not (zerop 4))
T

(not (zerop 0))
NIL

The AND Predicate in Lisp
The AND Predicate in Lisp takes two inputs, both of these must be true for it to evaluate and return T otherwise it returns NIL.
(and (> 6 4) (< 1 3))
T

Here only one of our predicates is true:
(and (numberp 6) (equalp 1 9))
NIL

The OR Predicate in Lisp
The OR Predicate in Lisp returns T if either one or both arguments are true:
(or (numberp 6) (equalp 1 9))
T

(or (> 7 6) (equalp 1 1))
T

Today's Lisp Challenge
Write a function called BETWEEN that takes 3 input arguments N, MIN and MAX. This function tests to see if N is between MIN and MAX.

Subscribe to Programming Lisp Tutorial Blog and check back to see the solution!