Skip to content

Instantly share code, notes, and snippets.

@overthink
Last active December 15, 2016 20:54
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 overthink/d81bab770fea9cef3471bc56cd4d111c to your computer and use it in GitHub Desktop.
Save overthink/d81bab770fea9cef3471bc56cd4d111c to your computer and use it in GitHub Desktop.
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) "...")
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