Skip to content

Instantly share code, notes, and snippets.

@mping
Forked from mping-exo/either.clj
Created February 15, 2021 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mping/c70a29c66a45c973e70cc97193ff9c40 to your computer and use it in GitHub Desktop.
Save mping/c70a29c66a45c973e70cc97193ff9c40 to your computer and use it in GitHub Desktop.
(require '[clojure.spec.alpha :as s])
(s/def ::test (s/and (s/keys :req-un [(or ::key1 ::key2)])
(fn [{:keys [key1 key2]}]
(not (and key1 key2)))))
;; s/or validates some of the keys
;; the (fn..) ensures that both keys CANNOT be present
user=> user=> (s/explain ::test {:key1 1 :key2 2 })
{:key1 1, :key2 2} - failed: (fn [{:keys [key1 key2]}] (not (and key1 key2))) spec: :user/test
nil
user=> (s/explain ::test {})
{} - failed: (or (contains? % :key1) (contains? % :key2)) spec: :user/test
nil
user=>
user=> (s/explain ::test {:key1 1 })
Success!
nil
user=> (s/explain ::test {:key2 2})
Success!
nil
;; CAVEAT: nils are allowed
user=> (s/explain ::test {:key1 nil :key2 2})
Success!
nil
;; for NIL handling, the anonymous function should check if the keys are NOT present, not their value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment