clojure-spec

About: http://clojure.org/about/spec Guide: http://clojure.org/guides/spec API: https://clojure.github.io/spec.alpha/clojure.spec.alpha-api.html
2020-02-24T21:53:32.004700Z

When conforming a sequence spec, can we guaranty key order? For instance:

(s/def ::a neg-int?)
(s/def ::b zero?)
(s/def ::c pos-int?)
(s/def ::sequence (s/cat :a ::a, :(s/? ::b), :c ::c))
I would like to use conform to know if the second element of the sequence is :b or :c (labels given in cat). conform returns a clojure.lang.PersistentHashMap, which does not key the keys in the same order as in the sequence.

seancorfield 2020-02-24T21:57:30.005600Z

s/conform just tells you how it matched. If you call s/valid? and get true then the input sequence is valid as is.

2020-02-24T21:59:19.007Z

I would have liked to use conform to parse the sequence and end up with {:a -2, :c 10}

seancorfield 2020-02-24T22:02:31.007900Z

Spec isn't really a "parser" but if you know your elements should be in a given order, you can easily manipulate the data you get from s/conform to produce a more appropriate structure.

seancorfield 2020-02-24T22:03:28.008600Z

(you know you're going to get :a first and :c last so the only question is (contains? conformed-data :b) to see if a zero is present...

2020-02-24T22:04:16.008900Z

ok thanks for your help!

alexmiller 2020-02-24T22:49:13.009700Z

s/tuple is a better match