Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Syntax and Evaluation

Conditionals and Equality

Make decisions in Common Lisp with if, when, unless, cond, case and typecase, understand NIL and truthiness, and choose between eq, eql, equal and equalp.

Programs need to choose. Common Lisp gives you a small core of conditional forms (if, cond, case, when, unless) and four equality predicates (eq, eql, equal, equalp) that confuse almost every newcomer. This lesson explains how truth works in Lisp, shows each form with examples, and ends with a clear rule for choosing an equality test.

Truth and NIL

In Common Lisp there is no separate boolean type. The rules are simple:

  • NIL is false.
  • Everything else is true, including 0, "" and the empty vector.
  • T is the standard "canonical true" value.
  • NIL is also the empty list: () and nil are the same object.
LISP
(if nil "yes" "no")     ; => "no"
(if 0 "yes" "no")       ; => "yes"   (zero is true!)
(if "" "yes" "no")      ; => "yes"
(if '() "yes" "no")     ; => "no"    the empty list is NIL
(null '())              ; => T
(not 5)                 ; => NIL

null and not are the same function in practice. By convention, use null when testing for an empty list and not for a general truth value, which makes your intent clear.

if

LISP
(if (> 5 3)
    "bigger"        ; then
    "smaller")      ; else (optional; omitted gives NIL)

if takes exactly one "then" form and at most one "else" form. For several forms, wrap them in progn:

LISP
(if (> x 0)
    (progn
      (format t "positive~%")
      (incf count))
    (format t "not positive~%"))

when and unless

When you have only one branch and several forms, use when (do these if true) and unless (do these if false). They contain an implicit progn.

LISP
(when (> x 0)
  (format t "positive~%")
  (incf count))

(unless (null items)
  (process items))

when returns the value of the last form, or NIL if the test failed.

cond

cond is the multi-way branch. Each clause is (test form...); the first test that is true wins:

LISP
(defun grade (score)
  (cond ((>= score 90) "A")
        ((>= score 80) "B")
        ((>= score 70) "C")
        (t "F")))            ; t as a test = "otherwise"

(grade 85)   ; => "B"

A clause with only a test returns the test's value, which makes it handy for lookups:

LISP
(cond ((assoc 'b '((a . 1) (b . 2))))   ; => (B . 2)
      (t :none))

Try cond, and, or, when on the Mini-Lisp, a JavaScript stand-in interpreter (not SBCL):

JS Mini-Lisp: cond, and, or, when

Press Run (or Ctrl + Enter) to see the console output here.

No output.

and, or

and and or are control-flow forms that short-circuit and return values, not just T or NIL.

LISP
(and 1 2 3)         ; => 3     returns the last value if all are true
(and 1 nil 3)       ; => NIL   stops at the first false
(or nil nil 7)      ; => 7     first true value
(or nil nil)        ; => NIL
(or (gethash k cache) (compute k))   ; classic "default" idiom

case and ecase

case compares a value against literal keys using eql. Keys are not evaluated:

LISP
(defun day-type (d)
  (case d
    ((:sat :sun) "weekend")        ; a list of keys
    (:fri "almost")
    (t "weekday")))                ; t or otherwise: default

(day-type :sun)   ; => "weekend"

Because case uses eql, it works for symbols, numbers and characters but not for strings; use cond with string= for those. ecase is the strict version: it signals an error if nothing matches, which catches typos early.

LISP
(ecase color
  (:red 1)
  (:green 2))     ; (ecase :blue ...) signals an error

typecase

typecase dispatches on the type of a value:

LISP
(defun describe-it (x)
  (typecase x
    (integer "an integer")
    (string  "a string")
    (list    "a list")
    (symbol  "a symbol")
    (t       "something else")))

(describe-it 42)       ; => "an integer"
(describe-it "hi")     ; => "a string"
(describe-it nil)      ; => "a list"   (NIL is a list, and listed first!)

Order matters: NIL is both a list and a symbol.

Four kinds of equality

Common Lisp separates the questions "are these the same object?" and "do these look the same?".

Predicate Question it answers
eq Are they the very same object (pointer comparison)?
eql Same object, or same number of the same type, or same character
equal eql, or structurally equal lists/strings/bit-vectors (case-sensitive)
equalp Like equal, but case-insensitive and numbers compare with =

Concrete cases:

LISP
(eq 'a 'a)                   ; => T     symbols are unique
(eql 3 3)                    ; => T
(eql 3 3.0)                  ; => NIL   different types
(eql "abc" "abc")            ; => NIL   two different string objects
(equal "abc" "abc")          ; => T
(equal '(1 2) '(1 2))        ; => T
(equal "abc" "ABC")          ; => NIL
(equalp "abc" "ABC")         ; => T
(equalp 3 3.0)               ; => T
(equalp #(1 2) #(1 2))       ; => T     vectors compared by elements
(= 3 3.0)                    ; => T     numeric only; errors on non-numbers

The stand-in below models the four predicates over a few value kinds so you can see exactly where they differ. It is JavaScript, not Lisp, and it is deliberately simplified.

JS Stand-in: eq, eql, equal, equalp

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note that for two different lists (1 2) the stand-in's eq is false because they are distinct objects: that is the behavior you should expect from real Lisp too.

Which one should I use?

  1. Symbols, small numbers, characters, keywords: eql (or eq for symbols).
  2. Numbers by value across types: =.
  3. Strings: string= (or equal); string-equal ignores case.
  4. Lists, trees, mixed data: equal.
  5. Case-insensitive, deep structure comparison: equalp.

The functions that take a :test argument (member, assoc, find, remove, gethash tables) default to eql, which is why (member "a" '("a" "b")) returns NIL and (member "a" '("a" "b") :test #'string=) does not:

LISP
(member 2 '(1 2 3))                         ; => (2 3)   eql works for numbers
(member "b" '("a" "b") )                    ; => NIL
(member "b" '("a" "b") :test #'equal)       ; => ("b")

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does (if 0 "yes" "no") return?

    Only NIL is false. Zero, empty strings and empty vectors are true.
  2. 2. What does (or nil nil 7) return?

    or returns the first true value it finds, not just T.
  3. 3. Which equality test is case-insensitive for strings?

    equalp ignores case in strings and compares numbers with =.
  4. 4. Why does (case "a" ("a" 1) (t 2)) return 2?

    case uses eql on unevaluated keys, so strings never match; use cond with string=.
  5. 5. What is (eql 3 3.0)?

    eql requires the same type; use = for numeric equality across types.

Summary

  • NIL is false and the empty list; every other value is true, including 0 and "".
  • if has one branch per side (use progn for more); when/unless have an implicit progn; cond is a multi-way branch ending with t.
  • and and or short-circuit and return values.
  • case uses eql on literal keys (not strings); ecase errors on no match; typecase dispatches on type.
  • eq identity, eql identity plus same-type numbers and characters, equal structure, equalp loose structure; = for numbers.

Next: Iteration with loop and do