Skip to content

Instantly share code, notes, and snippets.

@johnbendi
Last active August 29, 2015 14:22
Show Gist options
  • Save johnbendi/dcdc3c47ca14ac805285 to your computer and use it in GitHub Desktop.
Save johnbendi/dcdc3c47ca14ac805285 to your computer and use it in GitHub Desktop.
(defmacro when-let*
"simply implementation:
(if-let [[sym expr & more-bindings] (seq bindings)]
`(when-let [~sym ~expr]
(when-let* ~more-bindings ~@body))
`(do ~@body))
the form:
(when-let* [a 3 b 4] (+ a b))
will expanded as:
(when-let [a 3]
(when-let [b 4]
(+ a b)"
[bindings & body]
(letfn [(expand [bindings]
(if-let [[sym expr & more-bindings] (seq bindings)]
`(when-let [~sym ~expr]
~(expand more-bindings))
`(do ~@body)))]
(expand bindings)))
(defmacro if-let*
([bindings then]
`(when-let* ~bindings ~then))
([bindings then else]
(let [leted (vec (take-nth 2 bindings))
vals (take-nth 2 (rest bindings))
syms (vec (repeatedly (count leted) gensym))]
`(if-let [~leted (when-let* [~@(interleave syms vals)] ~syms)]
~then
~else))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment