Clojure binding of dynamic var not working as expected

后端 未结 3 1368
一生所求
一生所求 2020-12-11 20:53

From what I understand, setting a new binding on a dynamic var affects all functions called within that binding, and all functions called from those functions.

Why d

3条回答
  •  萌比男神i
    2020-12-11 21:33

    It's true that laziness and dynamic bindings can cause problems; however, abandoning laziness is not the only solution. If you wish to preserve laziness (or to use dynamic bindings with pmap), use bound-fn or bound-fn*.

    (def ^:dynamic x 0)
    
    => (binding [x 3] (map #(+ x %) (range 10)))
    ;; (0 1 2 3 4 5 6 7 8 9)
    
    => (binding [x 3] (map (bound-fn [y] (+ x y)) (range 10)))
    ;; (3 4 5 6 7 8 9 10 11 12)
    
    => (binding [x 3] (map (bound-fn* #(+ % x)) (range 10)))
    ;; (3 4 5 6 7 8 9 10 11 12)
    

提交回复
热议问题