Lambder
Lambder

Reputation: 2993

How do I limit size of generated sample with `clojure.spec/+`?

clojure.spec/coll-of takes :gen-max option to limit the generated sample size. Is there an analog for clojure.spec/+?

Upvotes: 4

Views: 493

Answers (1)

Taylor Wood
Taylor Wood

Reputation: 16194

s/* and s/+ don't take an option like :gen-max but those repetitive regex specs do take clojure.spec.alpha/*recursion-limit* into account. I think that's fairly coarse-grained control and has no practical effect on simple specs like this, which seemingly always generate a longest sequence of ~200 elements for any positive *recursion-limit*:

(binding [clojure.spec.alpha/*recursion-limit* 1]
  (->> (gen/sample (s/gen (s/* int?)) 200)
       (map count)
       (apply max)))

One way to limit the length of the generated sequences is to provide a custom generator:

(s/def ::ints
  (s/with-gen
    (s/+ int?)
    #(gen/vector gen/int 1 10)))
(gen/sample (s/gen ::ints) 200)

This should always generate a vector of 1-10 integers.

Upvotes: 1

Related Questions