Spec’ing Collections

We can also create specs for the various collections. The most basic here is coll-of, which specifies a collection of something:

 ;; Something like '("Alice" "In" "Wonderland").
 
 (​def​ coll-of-strings (s/coll-of string?))
 
 ;; Or a collection of numbers or strings, perhaps ["Emma" 1815 "Jaws" 1974]
 
 (​def​ coll-of-n-or-s (s/coll-of n-or-s))

To produce tighter specifications on collections, we can reach for cat. Essentially cat lets you specify this should follow that in a collection. For example, if we wanted to match only four-element collections consisting of alternating strings and numbers we could say this:

 (​def​ s-n-s-n (s/cat :s1 string? :n1 number? :s2 string? :n2 number?))
 
 (s/valid? s-n-s-n [​"Emma" ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.