On Feb 15, 2:44 pm, timc <timgcl...@gmail.com> wrote:
> I'm new to Clojure, just thought I would share this.
> I was playing around, trying to understand Atoms and I devised a
> function that generates the next value in the Fibonacci sequence each
> time it is called.
>
> (def fib-gen-val (atom [1 1]))
>
> (defn fib-gen []
> (let [[a b] @fib-gen-val]
> (swap! fib-gen-val #(let [[x y] %] (vector y (+ x y))))
> a))
>
> Repeated calls to fib-gen return 1 1 2 3 5 ...etc
>
> I could not figure out how to make a proper generator which somehow
> initializes its own secret internal state (atom).
You can write a "factory" function that, when called, generate a new
fib-gen closure, with a fresh fib-gen-val in its lexical scope:
(defn make-fib-gen [x y]
(let [fib-gen-val (atom [x y])]
(fn []
(let [[a b] @fib-gen-val]
(swap! fib-gen-val #(let [[x y] %] (vector y (+ x y))))
a))))
Regards,
--
Michel S.
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---