Skip to content

Instantly share code, notes, and snippets.

@pingles
Last active July 26, 2016 23:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pingles/5150585 to your computer and use it in GitHub Desktop.
Save pingles/5150585 to your computer and use it in GitHub Desktop.
Clojure if-let accepting multiple bindings
(ns if-let-multi-bind.core)
(defmacro if-let*
([bindings then]
`(if-let* ~bindings ~then nil))
([bindings then else & oldform]
(let [test (cons #'and (map last (partition 2 bindings)))]
`(if ~test
(let ~bindings
~then)
~else))))
(comment
(if-let* [a 1
b 3]
(+ a b))
;; 4
(if-let* [a 1
b nil]
(+ a b))
;; nil
(def x 1)
(def y false)
(if-let* [a x
b y]
[a b])
;; nil
)
@ertugrulcetin
Copy link

ertugrulcetin commented Jul 26, 2016

Here is the new if-let* imp:

(defmacro if-let*
  ([bindings then]
   `(if-let* ~bindings ~then nil))
  ([bindings then else]
   (if (seq bindings)
     `(if-let [~(first bindings) ~(second bindings)]
        (if-let* ~(drop 2 bindings) ~then ~else)
        ~(if-not (second bindings) else))
     then)))
(if-let* [a 1
           b (+ a 1) ]
           b)
;;=> 2
(if-let* [a 1
           b (+ a 1)
           c  false] ;;false or nil - does not matter
           b
           a)

;;=> 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment