Skip to content

Spec - 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)

clojure.core predicate functions

clojure.core defines 80+ predicate functions

Predicate functions in specsλ︎

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)