I've recently been trying out Clojure Spec and ran into an unexpected error message. I've figured out that if you have a spec/or nested in a spec/and then the spec functions, after the spec/or branch, get passed a conformed value rather than the top level value.
You can see this in the printed value of "v" here (contrived example):
(spec/valid? (spec/and (spec/or :always-true (constantly true))
(fn [v]
(println "v:" v)
(constantly true)))
nil)
v: [:always-true nil]
=> true
I think this may be intentional from the doc string of spec/and:
Takes predicate/spec-forms, e.g.
(s/and even? #(< % 42))
Returns a spec that returns the conformed value. Successive conformed values propagate through rest of predicates.
But this seems counterintuitive to me as it would hamper reuse of spec predicates, because they'd need to be written to accept "[<or branch> <actual value>]".
Things get even worse if you have multiple spec/or branches:
(spec/valid? (spec/and (spec/or :always-true (constantly true))
(spec/or :also-always-true (constantly true))
(fn [v]
(println "v:" v)
(constantly true)))
nil)
v: [:also-always-true [:always-true nil]]
=> true
Have I missed something fundamental here?
But this seems counterintuitive to me as it would hamper reuse of spec predicates
IMO the alternatives to these behaviors are less appealing:
s/or
's conformed tags by default. We can always discard it if we want, but we wouldn't want clojure.spec to make that decision for us. Spec assumes we want to know which s/or
branch matched.s/and
, at the expense of spec/predicate composability.Luckily we can discard the s/or
tags if necessary. Here are two options:
Wrap the s/or
in s/noncomforming
. Thanks to glts' comment below reminding me about this (undocumented) function!
(s/valid?
(s/and
(s/nonconforming (s/or :s string? :v vector?))
empty?)
"")
=> true
s/and
the s/or
specs with a s/conformer
that discards the tag.
(s/valid?
(s/and
(s/and (s/or :s string? :v vector?)
;; discard `s/or` tag here
(s/conformer second))
empty?)
[])
=> true
If you often needed this, you could reduce boilerplate with a macro:
(defmacro dkdc-or [& key-pred-forms]
`(s/and (s/or ~@key-pred-forms) (s/conformer second)))
Things get even worse if you have multiple spec/or branches
If you're writing a spec for data that allows for alternatives (e.g. s/or
, s/alt
), and you're "flowing" valid alternatives into subsequent predicates (s/and
), IMO it's more generally useful to have that knowledge in subsequent predicates. I'd be interested in seeing a more realistic use case for this type of spec, because there might be a better way to spec it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With