Last active
December 15, 2016 20:54
-
-
Save overthink/d81bab770fea9cef3471bc56cd4d111c to your computer and use it in GitHub Desktop.
Sort of nice nil checker in Clojure
This file contains hidden or 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
(defn- ellipses-if-long | |
"Append \"...\" to string version of x if x's length exceeds n." | |
([x] (ellipses-if-long x 50)) | |
([x n] | |
(assert (pos? n) "n must be positive") | |
(let [s (str x)] | |
(if (> (.length s) n) | |
(str (subs s 0 n) "...") | |
s)))) | |
(defmacro non-nil! | |
"If any of exprs evaluates to nil throw an exception containing a snippet of | |
the offending code in the message. Returns nil when it doesn't throw. Note | |
that each of exprs (until one evaluates to nil) will be evaluated here, so | |
don't use with side-effecting expressions." | |
[& exprs] | |
`(do | |
~@(for [expr exprs] | |
`(when (nil? ~expr) ; expr is actually evaluated here | |
(throw | |
(ex-info (format "'%s' evaluated to nil" | |
(ellipses-if-long '~expr)) | |
{:expr '~expr})))) | |
nil)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment