Search code examples
clojureplumatic-schema

Expression for "a member in set" with plumatic Schema


I want to write a schema where an element e in a data structure can be any member in a set S of items; e ∈ S. With Clojure Spec this is expressed with a set like:

(spec/def ::key-set #{:subprocess :leiningen :nrepl})
(gen/sample (spec/gen ::key-set))
; => (:nrepl :subprocess :subprocess :leiningen :subprocess :nrepl :subprocess :leiningen :nrepl :subprocess)

for a set of keywords.

In Schema however a set is used to denote a set of things rather than one element member of a set. So how do I in Schema express that I want one member out of a set?


Solution

  • schema.core/enum is what you're looking for.

    user=> (schema.core/validate (schema.core/enum "a" "b" "c") "a")
    "a"
    
    => (schema.core/validate (schema.core/enum "a" "b" "c") "z")
    clojure.lang.ExceptionInfo: Value does not match schema: (not (#{"a" "b" "c"} "z"))