Skip to content

Instantly share code, notes, and snippets.

Last active Dec 15, 2016
What would you like to do?
Sort of nice nil checker in Clojure
(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) "...")
(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]
~@(for [expr exprs]
`(when (nil? ~expr) ; expr is actually evaluated here
(ex-info (format "'%s' evaluated to nil"
(ellipses-if-long '~expr))
{:expr '~expr}))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment