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.
Desafíos de programación atemporales y multiparadigmáticos
Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.
Buy the bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.