On Dec 22, 5:24 am, "Brian Doyle" <brianpdo...@gmail.com> wrote:
> I haven't been following the new atom stuff, so I was wondering why atom
> would be best in this
> situation, vs a ref? Thanks.
Rich discusses the use of atoms, refs and agents in good detail
in this thread:
http://groups.google.com/group/clojure/msg/fd0371eb7238e933
In case you don't want multiple counters but just one,
the following can also be done.
user=> (let [n (atom 0)] (defn counter [] (swap! n inc)))
#'user/counter
user=> (counter)
1
user=> (counter)
2
user=> (counter)
3
Parth
>
> On Sun, Dec 21, 2008 at 1:03 PM, Parth Malwankar
> <parth.malwan...@gmail.com>wrote:
>
>
>
> > On Dec 21, 11:47 pm, chris <cnuern...@gmail.com> wrote:
> > > I would like to be able to encapsulate local state in a closure.
> > > Specifically, I would like a function that returns an incrementing
> > > integer, thus:
> > > (test_func)
> > > 1
> > > (test_func)
> > > 2
> > > What is the best way to go about this? With local bindings is failing
> > > and I can't figure just why...
>
> > One way to do this would be to use atom.
>
> > (defn mk-counter [start]
> > (let [n (atom start)]
> > (fn [] (swap! n inc))))
>
> > (def counter (mk-counter 0))
>
> > user=> (counter)
> > 1
> > user=> (counter)
> > 2
> > user=> (counter)
> > 3
>
> > Parth
> > > (def test_closure
> > > (with-local-vars [one 1]
> > > (fn [] (var-get one))))
> > > #'user/test_closure
> > > user> (test_closure)
> > > ; Evaluation aborted.
> > > The var is null when I call the closure.
>
> > > Thanks,
> > > Chris
--~--~---------~--~----~------------~-------~--~----~
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
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
-~----------~----~----~----~------~----~------~--~---