10. Predicates

Predicates are functions that return a boolean value: t (true) or nil (false). By convention, predicate names end with the letter p (or P in compound functions such as null-p, which is written nullp).

Common Lisp treats any value other than nil as true in boolean contexts, but by convention t is used to explicitly represent true.

* (if 42
      "42 es verdadero"
      "42 es falso")
"42 es verdadero"

* (if nil
      "nil es verdadero"
      "nil es falso")
"nil es falso"

Some basic predicates for working with types:

* (null nil)
T

* (null '())
T

* (null '(a b c))
NIL

* (atom 'a)
T

* (atom '(a b))
NIL

* (listp '(a b c))
T

* (listp 'a)
NIL

* (consp '(a b c))
T

* (consp nil)
NIL

The difference between listp and consp is subtle: listp returns true both for lists and for nil (the empty list), while consp only returns true for non-empty lists (cons cells).

Numeric predicates:

* (zerop 0)
T

* (plusp 5)
T

* (minusp -3)
T

* (evenp 4)
T

* (oddp 3)
T

* (numberp 42)
T

* (integerp 3.14)
NIL

Comparison predicates:

* (= 5 5)
T

* (= 5 3)
NIL

* (/= 5 3)
T

* (< 3 5)
T

* (> 10 2)
T

* (<= 5 5)
T

* (>= 10 5)
T

The = predicate only works with numbers. To compare other types, use eq, eql, equal, or equalp.

To compare symbols and references:

* (eq 'a 'a)
T

* (eql 5 5)
T

* (equal '(a b c) '(a b c))
T

* (equalp "Hola" "hola")
T

The differences are: - eq: compares whether two objects are the same object in memory (identity). - eql: like eq, but also works correctly with numbers and characters of the same value. - equal: compares structurally (lists, strings, etc.). - equalp: like equal, but ignores case differences in strings and compares numbers of different types.

Logical operators to combine predicates:

* (and t t)
T

* (and t nil)
NIL

* (or nil t)
T

* (or nil nil)
NIL

* (not t)
NIL

* (not nil)
T

These operators evaluate lazily (short-circuit evaluation):

* (and (> 5 3) (< 2 10))
T

* (or (> 5 10) (< 2 10))
T
Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.

Buy the book

Help me keep writing

Every coffee gives me a push toward the next article.

Comments

There are no comments yet.