Search code examples
clojureplumatic-schema

Can one make a predicate function from a Plumatic Schema?


I want to make a predicate function that when something matches schema X returns true, else false.


Solution

  • You can use schema/check which works like schema/validate but returns errors directly as a value instead of throwing exception or nil when no errors are found:

    (schema/defschema string-vector
      [schema/Str])
    
    (defn str-vec? [arg]
      (nil? (schema/check string-vector arg)))
    
    (str-vec? ["hi"])   ; => true
    (str-vec? ["hi" 5]) ; => false
    

    There is also schema/checker which "compiles an efficient checker for schema":

    (let [str-vec?-checker (schema/checker string-vector)]
      (defn str-vec? [arg]
        (nil? (str-vec?-checker arg))))