I am new to Clojure and have been working through some of the examples on the PCL -> Clojure blog. Currently I am working through Chapter 6 (variables).
The blog says "Nothing stops multiple functions from closing on the same variables. Here is a function that returns an incrementer, decrementer, and accessor, all sharing the same counter:" (defn counters [] (let [count (ref 0)] (list #(dosync (alter count inc)) #(dosync (alter count dec)) #(deref count)))) I tried to this example (with Clojure 1.3.0 and 1.2.1) and found that it does not appear to work, or I am totally missing something. Here is some output from a REPL session using this function. Could you help me understand the output or, if there is a mistake in the example, could you explain what it is? Question 1: I expected these two statements to produce output 1, 2 user=> ((nth (counters) 0)) 1 user=> ((nth (counters) 0)) 1 Question 2: So then I did the following: user=> (def a (nth (counters) 0)) #'user/a user=> (def b (nth (counters) 2)) #'user/b user=> (a) 1 user=> (a) 2 user=> (a) 3 user=> (b) 0 Now the incrementer appears to be working, but then when I try to use the accessor to inspect the value of "count", it is still 0. So it appears that the 3 anonymous functions in the list are not closing over "count". Could somebody help me understand this behavior? Thank you for your help. matthew -- 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