LISP - Numeric Predicates
Lisp - Numeric Predicates
Section titled “Lisp - Numeric Predicates”Numeric predicates are functions that test a number for a specific property and return a boolean value (T for true, nil for false). They are fundamental building blocks for logic and control flow in any Lisp program.
Here are the most common numeric predicates:
| Predicate | Description |
|---|---|
evenp number | Returns T if number is an even integer, nil otherwise. |
oddp number | Returns T if number is an odd integer, nil otherwise. |
zerop number | Returns T if number is zero, nil otherwise. Works for integers and floats. |
plusp number | Returns T if number is strictly positive (> 0), nil otherwise. |
minusp number | Returns T if number is strictly negative (< 0), nil otherwise. |
Example: Using Core Numeric Predicates
Section titled “Example: Using Core Numeric Predicates”The following code demonstrates each of these predicates in action. The comments show the expected return value as you would see in a REPL.
main.lisp
Section titled “main.lisp”;; --- evenp and oddp ---(evenp 10) ; => T(evenp 7) ; => NIL(oddp 7) ; => T(oddp 10) ; => NIL
;; --- zerop ---(zerop 0) ; => T(zerop 0.0) ; => T(zerop 100) ; => NIL
;; --- plusp ---(plusp 55) ; => T(plusp 0.1) ; => T(plusp 0) ; => NIL(plusp -5) ; => NIL
;; --- minusp ---(minusp -99) ; => T(minusp -0.5) ; => T(minusp 0) ; => NIL(minusp 99) ; => NILPractical Application: Control Flow
Section titled “Practical Application: Control Flow”Predicates are most useful for controlling the flow of your program using conditionals like if and cond.
main.lisp
Section titled “main.lisp”(defun describe-number (n) (cond ((zerop n) "The number is zero.") ((minusp n) "The number is negative.") ((plusp n) (if (evenp n) "The number is positive and even." "The number is positive and odd.")) (t "This is not a real number."))) ; Fallback case
(print (describe-number -10))(print (describe-number 7))(print (describe-number 0))Output
Section titled “Output”"The number is negative.""The number is positive and odd.""The number is zero."Beyond the Basics: Type and Comparison Predicates
Section titled “Beyond the Basics: Type and Comparison Predicates”While the functions above check properties, another important category of predicates checks for type and equality.
- Type Predicates:
numberp,integerp,floatp, andrationalpcheck if an object is of a specific numeric type. - Comparison Predicates: The functions
=,/=,<,>,<=, and>=are also predicates. They are used for numeric comparison and can take multiple arguments. For example,(< 1 5 10)returnsTbecause 1 is less than 5, and 5 is less than 10.
Example
Section titled “Example”(numberp 10) ; => T(floatp 3.14) ; => T(integerp 3.14) ; => NIL
(= 5 5 5) ; => T(/= 5 6 7) ; => T (all are different from each other)(<= 1 2 2 3) ; => T