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.

  1. 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 have rlwrap installed or clojure to run a very basic Clojure REPL.

Require the clojure.spec.alpha using an alias called spec to use functions from that namespace.

  1. (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.

Clojure REPL - rebel readline autocompletion for spec

Typing a space character after the full name of a function shows the function signature with arguments that should be passed to that function.

Clojure REPL - reble readline spec funciton signature

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.

Clojure REPL - rebel readline spec examples

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.

  1. (spec/conform odd? 101)
  2. (spec/conform integer? 1)
  3. (spec/conform seq? [1 2 3])
  4. (spec/conform seq? (range 10))
  5. (spec/conform map? {})
  6. (spec/conform map? (hash-map :a 1 :b 2))

spec/valid? returns true or false

  1. (spec/valid? even? 180)
  2. (spec/valid? string? "Am I a valid string")
  3. (spec/valid? (fn [value] (> value 10000)) 30076)
  4. (spec/valid? #(> % 10000) 30076)
  5. (spec/conform #(> % 10000) 30076)