Bindings and send

utilities — cgrand, 20 January 2009 @ 19 h 50 min

This morning on #clojure erohtar asked:

what is the best way to bind vars to a value when sending to an agent?

I don’t know if it’s the best way but it’s mine:

(defmacro capture-and-send
 "Capture the current value of the specified vars and rebind 
  them on the agent thread before executing the action."
 [vars agent action & args]
  (let [locals (map #(gensym (name %)) vars)]
    `(let [~@(interleave locals vars)
           action# (fn [& args#]
                     (binding [~@(interleave vars locals)]
                       (apply ~action args#)))]
       (send ~agent action# ~@args))))
;; usage:
(capture-and-send [*out*] a f b c)

I post it here because erohtar needed it, I needed it once so others may need it.


No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

(c) 2024 Clojure and me | powered by WordPress with Barecity