Fork me on GitHub
#clojure-spec
<
2020-09-24
>
Jeff Evans15:09:17

From the guide: https://clojure.org/guides/spec#_custom_generators I’m trying to figure out whether it’s possible to refer to kw-gen (which was just defined in the previous section) here, but I can’t quite figure out the right syntax. For instance, this doesn’t work:

(s/def ::kws (s/with-gen (s/and keyword? #(= (namespace %) "my.domain")) #(kw-gen)))

Alex Miller (Clojure team)16:09:46

user=> (def kw-gen (s/gen #{:my.domain/name :my.domain/occupation :my.domain/id}))
#'user/kw-gen
user=> (s/def ::kws (s/with-gen (s/and keyword? #(= (namespace %) "my.domain")) (fn [] kw-gen)))
:user/kws
user=> (gen/sample (s/gen ::kws))
(:my.domain/name :my.domain/id :my.domain/name :my.domain/name :my.domain/name :my.domain/occupation :my.domain/occupation :my.domain/occupation :my.domain/id :my.domain/occupation)

Alex Miller (Clojure team)16:09:18

kw-gen here is a generator so you need to wrap it in a no-arg function that returns it (not invokes it)

Jeff Evans17:09:36

thanks! I misunderstood something fundamental, since I thought #(kw-gen) was equivalent to (fn [] kw-gen)

Alex Miller (Clojure team)17:09:34

the former is the same as (fn [] (kw-gen))

👍 3
Alex Miller (Clojure team)17:09:37

I guess you could also do (constantly kw-gen)