有没有办法在Clojure中进行顺序绑定?

时间:2011-07-15 18:36:14

标签: clojure

我想使用binding宏,但希望它像let一样顺序。

我想我可以这样写......

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

......但是必须有更好的方法。有什么想法吗?

1 个答案:

答案 0 :(得分:8)

(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])))