On Wednesday, August 8, 2012 6:48:23 PM UTC+2, Brian Marick wrote:
>
> ... show the mechanics, but I'm looking for examples that would resonate 
> more with an object-oriented programmer. Such examples might be ones that 
> close over a number of values (which looks more like an object), or 
> generate multiple functions that all close over a shared value (which looks 
> more like an object), or use closures to avoid the need to have some 
> particular argument passed from function to function (which looks like the 
> `this` in an instance method). 
>

You can make objects with its state hidden in a closure. E.g. if we want to 
make a stack where people cannot look at any other element than the first 
one, we can do that like this:

(letfn [(stack-fns [stack]
          {:push (fn [elt] (stack-fns (conj stack elt)))
           :pop (fn [] (stack-fns (pop stack)))
           :peek (fn [] (peek stack))
           :empty? (fn [] (empty? stack))})]
  (defn new-stack []
    (stack-fns [])))

Usage would be like this:

(let [stack (reduce
             #((%1 :push) %2)
             (new-stack)
             (range 1 10))] ; To fill it with data
  (loop [stack stack]
    (if ((stack :empty?))
      nil
      (let [h ((stack :peek))
            t ((stack :pop))]
        (prn h)
        (recur t)))))

And this will print the numbers 9 to 1, before returning nil.

The Joy of Clojure looks at this from p. 138 to 141, so I take no credit 
for the idea - give that to the authors.

-- 
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

Reply via email to