-
-
Save krstoff/7ccdf387bc50caeb071e9d1b18f03024 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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