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
listpandconspis subtle:listpreturns true both for lists and fornil(the empty list), whileconsponly 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, useeq,eql,equal, orequalp.
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
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
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 bookHelp me keep writing
Every coffee gives me a push toward the next article.
Sure, it's on me!
Comments
There are no comments yet.