On Sun, Aug 2, 2015 at 4:38 AM, Divyansh Prakash <
divyanshprakas...@gmail.com> wrote:

> I have one more question, though: how does one work in ClojureScript
> without <!! ?
>
>

This use case is a little weird because the <!! is being done to block the
function until the reduction is complete, thus making pi appear externally
like a pure function.

In Clojurescript, you really don't want to block your main thread to read a
channel, because browsers are single-threaded and this will lock up your
whole page.  So in Clojurescript, you'd probably only use this channel
architecture if you wanted to compute pi, and then when it is ready, render
the answer to the webpage.  In that case, you'd just do:

(def browser-state-atom (atom {}))

(defn pi [n]
  (let [ch (to-chan (map term (range (inc n))))]
    (go (swap! browser-state-atom assoc :pi (<! (async/reduce + 0.0 ch))))))

and then use something like reagent to detect the change in the :pi portion
of the atom and render the result to the page.  Or you could get clever,
and render the results as they are being added up:
(defn pi [n]
  (let [ch (to-chan (map term (range (inc n))))]
    (go-loop []
             (when-let [v (<! ch)]
               (swap! browser-state-atom update :pi (fnil (partial + v)
0.0))
               (recur)))))

If, for some reason, you really wanted to sit and spin in a loop, blocking
for the result to complete, so you can mimic the behavior of the clojure
version, I think you could sit in a loop and use the async function take!
with the variant that calls a callback function only if a value is
immediately available on the channel.  So in that callback you mark some
variable with the final result of the reduction, and you only exit the loop
once that result is available.

-- 
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
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to