Skip to content

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:

PredicateDescription
evenp numberReturns T if number is an even integer, nil otherwise.
oddp numberReturns T if number is an odd integer, nil otherwise.
zerop numberReturns T if number is zero, nil otherwise. Works for integers and floats.
plusp numberReturns T if number is strictly positive (> 0), nil otherwise.
minusp numberReturns T if number is strictly negative (< 0), nil otherwise.

The following code demonstrates each of these predicates in action. The comments show the expected return value as you would see in a REPL.

;; --- 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) ; => NIL

Predicates are most useful for controlling the flow of your program using conditionals like if and cond.

(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))
"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, and rationalp check 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) returns T because 1 is less than 5, and 5 is less than 10.
(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