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-09-24T15:53:17.002100Z

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)))

alexmiller 2020-09-24T16:38:46.002400Z

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)

alexmiller 2020-09-24T16:39:18.002800Z

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

2020-09-24T17:30:36.003600Z

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

alexmiller 2020-09-24T17:34:34.003900Z

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

👍 1
alexmiller 2020-09-24T17:35:37.004300Z

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