Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Some `if`/`when` helpers. Don't need these often (and avoid them whenever possible), but they're occasionally handy when dealing with particularly hairy code.
(defmacro iff [test & {:keys [then else]}] `(if ~test ~then ~else))
(comment (iff false
:then (println "true")
:else (println "false")))
(defmacro iff-let [bindings & {:keys [then else]}] `(if-let ~bindings ~then ~else))
(comment (iff-let [x true] :else "false" :then x))
(defmacro if-lets
"Like `if-let` but binds multiple values iff all tests are true."
([bindings then] `(if-lets ~bindings ~then nil))
([bindings then else]
(let [[b1 b2 & bnext] bindings]
(if bnext
`(if-let [~b1 ~b2] (if-lets ~(vec bnext) ~then ~else) ~else)
`(if-let [~b1 ~b2] ~then ~else)))))
(comment (if-lets [a :a] a)
(if-lets [a nil] a)
(if-lets [a :a b :b] [a b])
(if-lets [a :a b nil] [a b]))
(defmacro iff-lets [bindings & {:keys [then else]}] `(if-lets ~bindings ~then ~else))
(defmacro when-lets
"Like `when-let` but binds multiple values iff all tests are true."
[bindings & body]
(let [[b1 b2 & bnext] bindings]
(if bnext
`(when-let [~b1 ~b2] (when-lets ~(vec bnext) ~@body))
`(when-let [~b1 ~b2] ~@body))))
(comment (when-lets [a :a b nil] "foo"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.