Repeatedly or binding

(def ^:dynamic *d* 1)

(binding [*d* 2]
  (println *d*)
  (repeatedly 1 #(println *d*)))

Conclusion:

2
1

Why? Why does the function inside repeatedlysee the value of dynamic var out binding?

By the way, I checked (.getId (java.lang.Thread/currentThread))inside and outside the anonymous function: this is the same.

+4
source share
1 answer

the lazy sequence created repeatedlyis returned from the form and then implemented only when printing via REPL after the binding has been "unwound", and just at that moment an anonymous function is called. To make sure this is the case, try these two options:

(binding [*d* 2]
  (println *d*)
  (let [x (repeatedly 1 #(println *d*))]
    (println (realized? x))
    x))

and

(binding [*d* 2]
  (println *d*)
  (doall (repeatedly 1 #(println *d*))))

The second variation causes the sequence to be fully implemented while still within the bounding area.

, "" bound-fn:

(binding [*d* 2]
  (println *d*)
  (repeatedly 1 (bound-fn [] (println *d*)))) 
+9

Source: https://habr.com/ru/post/1692677/


All Articles