Skip to content

Instantly share code, notes, and snippets.

@ptaoussanis
Created July 31, 2013 11:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptaoussanis/6121224 to your computer and use it in GitHub Desktop.
Save ptaoussanis/6121224 to your computer and use it in GitHub Desktop.
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