Predicate functions
A predicate is a function that returns a true or false value and their names end with ?
by convention.
(odd? 1)
(string? "am i a string")
(int? 2.3)
(int? 2.3)
Hint::
clojure.core
predicate functionsThere are 80+ predicate functions in
clojure.core
Using predicate functions as specifications
Predicate functions can be used as un-named specifications to test values conform.
Include the clojure.spec.alpha
namespace to access the spec functions.
(require '[clojure.spec.alpha :as spec])
(spec/conform int? 42)
(spec/conform seq? (range 4))
Custom predicate functions
Define custom predicate functions with defn
or fn
or the short form #()
Using an anonymous function
(spec/conform (fn [value] (= value 42)) 42)
When the expression is quite terse, then the short form of an anonymous function is typically used. The %
represents the value passed as an argument.
(spec/conform #(= % 42) 42)
当前内容版权归 practicalli 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 practicalli .