Using Clojure Spec in the REPL
Clojure 1.10.x or greater includes the clojure.spec.alpha library. clojure -Sdescribe
in a terminal will show the version of Clojure.
Run a Clojure REPL in a terminal window from your operating system using rebel readline.
clojure -A:rebel
Hint::Rebel Alias in practicalli/clojure-deps
Review or clone the practicalli/clojure-deps repository to include the alias to run rebel readline powered Clojure REPL. Alternative use
clj
if you haverlwrap
installed orclojure
to run a very basic Clojure REPL.
Require the clojure.spec.alpha
using an alias called spec
to use functions from that namespace.
(require '[clojure.spec.alpha :as spec])
Use (in-ns 'namespace.name)
if you need to change into a specific namespace.
Spec auto-completion
Using rebel-readline for the Clojure REPL will show autocompletion for all spec functions once the spec namespace has been required.
Type (spec /
and press TAB
to list all the functions in the namespace.
Typing a space character after the full name of a function shows the function signature with arguments that should be passed to that function.
Check data conforms to the specification
Use the spec/conform
and spec/valid?
functions to test if data matches a specification. In these examples, predicate functions are used as a specification.
Try examples in the REPL
spec/conform
will return the value if it conforms to the specification, or :clojure.spec.alpha/invalid
if the data does not conform.
(spec/conform odd? 101)
(spec/conform integer? 1)
(spec/conform seq? [1 2 3])
(spec/conform seq? (range 10))
(spec/conform map? {})
(spec/conform map? (hash-map :a 1 :b 2))
spec/valid?
returns true or false
(spec/valid? even? 180)
(spec/valid? string? "Am I a valid string")
(spec/valid? (fn [value] (> value 10000)) 30076)
(spec/valid? #(> % 10000) 30076)
(spec/conform #(> % 10000) 30076)