Ken Wesson <kwess...@gmail.com> writes:

> On Tue, Nov 30, 2010 at 5:27 PM, Robert McIntyre <r...@mit.edu> wrote:
>> (defn runonce
>>  "Create a function that will only run once. All other invocations
>>  return the first calculated value. The function can have side effects.
>>  Returns a [has-run-predicate, reset-fn, once-fn]"
>>  [function]
>>  (let [sentinel (Object.)
>>        result (atom sentinel)
>>        reset-fn (fn [] (reset! result sentinel) nil)
>>        has-run? #(not= @result sentinel)]
>>    [has-run?
>>     reset-fn
>>     (fn [& args]
>>       (locking sentinel
>>         (if (= @result sentinel)
>>           (reset! result (function))
>>           @result)))]))
>
> Eww. Why (locking ...)? Why not just (swap! result #(if (= % sentinel)
> (function) %))?

>From the doc string: "The function can have side effects."

Sometimes a lock is the right tool for the job.

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