Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to do sequential bindings in Clojure?

Tags:

clojure

I want to use the binding macro, but want it to be sequential like in let.

I guess I can write it like this...

(binding [a 1]
  (binding [b (inc a)]
    (println b))) 

...but there's gotta be a better way. Any thoughts?

like image 382
funkymunky Avatar asked Jul 15 '11 18:07

funkymunky


1 Answers

(defmacro binding* [bindings & body]
  (reduce (fn [acc [x y]]
            `(binding [~x ~y] ~acc))
          `(do ~@body)
          (reverse (partition 2 bindings))))

user> (declare ^:dynamic a ^:dynamic b)
#'user/b
user> (binding* [a 1 b (inc a)] [a b])
[1 2]

user> (macroexpand-1 '(binding* [a 1 b (inc a)] [a b]))
(clojure.core/binding [a 1]
 (clojure.core/binding [b (inc a)] 
  (do [a b])))
like image 131
Brian Carper Avatar answered Oct 30 '22 09:10

Brian Carper