Re: Explanation of with-resource
Brilliant, thanks Meikel! Quite a complex macro, that. -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en
Re: Explanation of with-resource
Hi, (defmacro with-resources [bindings close-fn & body] (let [[x v & more] bindings] `(let [~x ~v] (try ~(if-let [more (seq more)] `(with-resources ~more ~close-fn ~@body) `(do ~@body)) (finally (~close-fn ~x)) user=> (macroexpand-1 '(with-resources [x 1] close foo bar)) (clojure.core/let [x 1] (try (do foo bar) (finally (close x user=> (macroexpand-1 '(with-resources [x 1 y 2] close foo bar)) (clojure.core/let [x 1] (try (user/with-resources (y 2) close foo bar) (finally (close x You can call with-resource recursively. This has the added benefit of closing the resources in reverse order. Sincerely Meikel -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en
Explanation of with-resource
Hi Clojurians! Please could somebody explain the code highlighted expression below to me? (Adapted from *The Joy of Clojure*, listing 8.9) (defmacro with-resource [bindings close-fn & body] > `(let ~bindings > (try >~@body >(finally > (~close-fn ~(bindings 0)) I've changed the name of the variable from binding to bindings as I originally thought this was calling the function binding! I've also removed the redundant do loop. Using macroexpand-1 on the code yields the following: user> (macroexpand-1 '(with-resource [x 1] #(println %))) > (clojure.core/let [x 1] (try (finally ((fn* [p1__1605#] (println > p1__1605#)) x It seems like the highlighted expression is indexing into the let vector at position 0. Neat trick, but this doesn't seem to work when multiple variables are being bound by the let. So how would one modify with-resource to call close-fn with multiple variables? Regards, Ralph -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en