Skip to content

Instantly share code, notes, and snippets.

@krstoff
Last active July 19, 2021 09:58
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 krstoff/7ccdf387bc50caeb071e9d1b18f03024 to your computer and use it in GitHub Desktop.
Save krstoff/7ccdf387bc50caeb071e9d1b18f03024 to your computer and use it in GitHub Desktop.
(defmacro check
"Takes an expression and optional test functions,
returning the value of the expr if it is non-nil and passes the tests,
throwing an exception otherwise.
Examples:
(check (+ 1 2) (partial = 3)) => 3
(check (+ 1 2) (partial odd?) (partial even?) => throws Exception
(check (.toUpperCase \"okay\")) => \"OKAY\"
(check nil) => throws Exception"
([expr & tests]
(let [tests# (map (fn [t] [t (str t)]) tests)] ;; need both the test and its form
`(let [value# ~expr]
(doseq [[test# test-form#] [~@tests#]]
(when (not (test# value#))
(throw (Exception.
(str (quote ~expr)
" failed check: " test-form#
" with value: " value#)))))
value#)))
([expr]
(let [value# expr]
`(if ~value# ~value#
(throw (Exception. (str (quote ~expr) " was nil")))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment