Fork me on GitHub
#clojure-spec
<
2022-05-06
>
West04:05:54

(s/def ::params (s/or :string string?
                      :map map?))

(defn is-null? [val]
  (or (empty? val)
      (= "null" val)
      (nil? val)))

(s/def ::non-null-params
  (s/and ::params
         #(not (is-null? %))))

(gen/sample (s/gen ::non-null-params))
Why does ::non-null-params still give me empty maps and empty strings?

seancorfield04:05:10

Because s/or produces a pair. Either [:string s] or [:map m]

seancorfield04:05:33

is-null? could have [[_ val]] as its arglist and it will work.

seancorfield04:05:10

Or you could test (is-null? (second %))

West04:05:25

Ah ok. Then clearly I didn't want to use s/or I wanted to choose one or the other.

seancorfield04:05:30

(technically it's a MapEntry so (val %) is "more correct" than (second %)

seancorfield04:05:54

s/or is how you do it, but it returns a tagged pair to tell you which branch matched.

West04:05:28

(s/def ::non-null-params
  (s/and ::params
         #(not (is-null? (val %)))))
Thanks Sean. It's working just as expected!

seancorfield04:05:32

I think Alex has said that Spec 2 will have a non-conforming or that doesn't do that, or at least some easy way to avoid it...

West04:05:44

"Will have", as in "when it's released", or "is being talked about". Can I test it now?

seancorfield04:05:51

It's only available via git deps and it's kind of buggy.

West04:05:46

Alright, maybe an adventure for another day.

seancorfield04:05:48

What you can do with Spec 1 is used the undocumented nonconforming function, which is currently documented for Spec 2 (but might go away -- it will still be in Spec 1 tho'):

(s/def ::params (s/nonconforming (s/or :string string? :map map?)))

seancorfield04:05:57

Spec 1 isn't going away. Spec 2 will most likely morph into the actual "core" Spec at some point and folks will either migrate from Spec 1 to "Spec" or use both side-by-side.

seancorfield04:05:04

For a while at work, we maintained a branch of our code base migrated to use Spec 2, and help Alex test stuff, but it was such a moving target and several places were buggy and/or incomplete so after several months we abandoned trying to keep our branch updated and decided to wait for Spec 2 to mature.

seancorfield04:05:00

Spec 2 has a lot of improvements over Spec 1 but it is also quite different in several places.

West04:05:21

Either way, I'm excited to see how it turns out.

💯 1