user483036
user483036

Reputation:

How to define a sequence of equal sized collections with spec? (is it possible?)

I wish to represent a sequence of collections of strings. The inner collections should all have same length.

My initial attempt looks like this

(s/def ::stuff (s/every (s/coll-of string?) :min-count 1))

But when I exercise this I get inner collections of varying length.

Is there a declarative way to specify that the lengths should all be the same? Or can this only be specified in a custom generator function for the spec?

Upvotes: 1

Views: 161

Answers (1)

Alex Miller
Alex Miller

Reputation: 70239

I would state the spec as something like

(s/def ::stuff 
  (s/and 
    (s/every (s/coll-of string?)) 
    #(or (empty? %) 
         (apply = (map count %)))))

That will likely gen, but most of things you'll get will either be an empty collection or a collection of one element, which both trivially pass the length constraint. For that you'll need a custom gen.

Upvotes: 2

Related Questions