Skip to content

Instantly share code, notes, and snippets.

@attentive
Last active March 11, 2019 08:56
Show Gist options
  • Save attentive/878d7971721aa5464c39e957fa9a88a5 to your computer and use it in GitHub Desktop.
Save attentive/878d7971721aa5464c39e957fa9a88a5 to your computer and use it in GitHub Desktop.
Unexpected clojure.spec behaviour
(namespace foo.core
(:require [clojure.spec.alpha :as s]))
(s/def ::n (s/or :integer integer? :string string?))
(s/def ::m (s/keys :req-un [::n]))
(defn m-even? [m] (even? (:n m)))
(s/def ::m-even (s/and ::m m-even?))
(s/valid? ::m {:n 2}) ;; => true
(s/valid? m-even? {:n 2}) ;; => true
(s/valid? ::m-even {:n 2}) ;; => false
(s/explain ::m-even {:n 2}) ;; => #object[Error Error: Argument must be an integer: [object Object]]
;; To resolve this, the predicate m-even? must be applied to the "unformed" conformed value
(def m-even-with-unform? (comp m-even? (partial s/unform ::m)))
(s/def ::m-even-with-unform (s/and ::m m-even-with-unform?)
(s/valid? ::m-even-with-unform {:n 2}) ;; => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment