This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2023-02-15
Channels
- # announcements (5)
- # babashka (56)
- # beginners (24)
- # biff (15)
- # calva (7)
- # clj-kondo (12)
- # cljsrn (8)
- # clojure (68)
- # clojure-denmark (1)
- # clojure-europe (55)
- # clojure-norway (4)
- # clojure-spec (9)
- # clojure-uk (2)
- # clojurescript (8)
- # cursive (11)
- # data-science (7)
- # datahike (1)
- # datomic (66)
- # emacs (12)
- # etaoin (3)
- # fulcro (10)
- # graphql (3)
- # hyperfiddle (97)
- # jobs (1)
- # kaocha (8)
- # lsp (3)
- # malli (15)
- # meander (1)
- # off-topic (3)
- # overtone (4)
- # polylith (7)
- # rdf (25)
- # re-frame (4)
- # reagent (14)
- # remote-jobs (1)
- # shadow-cljs (126)
- # sql (30)
- # vscode (3)
- # xtdb (8)
Hey team, noob question. Consider the following object:
(s/def ::type #{:foo :bar})
(s/def ::obj (s/keys :req [::type ::a ::b] :opt [::c]))
How would I express something like: If ::type
is :foo, ::c
is required, but otherwise it's not?you can s/and
a function that tests any property you like
but you might also want to look at s/multi-spec
https://clojure.org/guides/spec#_multi_spec
Nice! Thanks @U064X3EF3!
Hey @U064X3EF3 one more question:
(s/def ::type #{:biz :baz})
(s/def ::foo string?)
(s/def ::bar string?)
(s/def ::kux string?)
(s/def ::common (s/keys :req [::type ::foo ::bar]))
(s/def ::biz-obj ::common)
(s/def ::baz-obj
(s/merge ::common
(s/keys :req [::kux])))
(defmulti type-mm ::type)
(defmethod type-mm :biz [_] ::biz-obj)
(defmethod type-mm :baz [_] ::baz-obj)
(s/def ::obj (s/multi-spec type-mm ::type))
(gen/generate (s/gen ::obj)))
Here I make it so if the type is :baz, then ::kux is required.
But one thing I did want to do:
Sometimes I want to generate the different instances of the objects -- i.e ::biz-obj and ::baz-obj
But the way I wrote it, I would get an invariant. If I wrote:
(gen/generate (s/gen ::biz-obj)))
I would sometimes get values with ::type :baz
This is because I don't constraint the type in this layer.
I guess I have two questions: Is this the right approach? And if so, how would I go about properly constructing ::biz-obj and ::baz-obj?well you could constrain the type in those layers
or make a generator that inserted the expected type
using gen/fmap
One question for my learning: How would I constrain the type in those layers?
(s/def ::biz-obj (s/keys :req [::type ::foo ::bar]))
(s/def ::baz-obj
(s/merge ::biz-obj
(s/keys :req [::kux])))
Since these are both s/keys
, and they both must take ::type
as one of the validations, how would I say "for this map, ::type
is just this part"?
Or did you have something else in mind?