Fork me on GitHub
#clojure-spec
<
2017-09-27
>
waffletower01:09:25

Is there a better way to parameterize generators than to use macros? In this case, I’d like to reuse a generator in different specs with different parameters:

(defmacro limited-string-m [lim]
  `(gen/such-that (fn [s#]
                    (not (blank? s#)))
                  (gen/sized
                   (fn [size#]
                     (gen/resize (dec ~lim) gen/string-alphanumeric)))))

gfredericks10:09:42

@waffletower at a glance that looks like a macro that could trivially be a function you don't generally need to write any macros to build generators

mrchance11:09:42

@stathissideris oh nice, that looks like a helpful recommendation in any case!

waffletower16:09:13

@gfredericks Thanks! works as a function as well

waffletower16:09:47

(defn limited-string-fn [lim]
  (gen/such-that (fn [s]
                    (not (blank? s)))
                  (gen/sized
                   (fn [size]
                     (gen/resize (dec lim) gen/string-alphanumeric)))))

gfredericks16:09:42

@waffletower btw, if you want to retain the gradual-growth property of the builtin generator, you could replace (gen/resize (dec lim) ...) with (gen/scale #(min % (dec lim)) ...)

waffletower16:09:46

thanks, I had noticed that side effect