Quantcast
Channel: How to update an atom from multiple future(s) in Clojure? - Stack Overflow
Viewing all articles
Browse latest Browse all 3

How to update an atom from multiple future(s) in Clojure?

$
0
0

I was trying to do the following exercise from Brave Clojure book:

Create a function that uses futures to parallelize the task of downloading random quotes from http://www.braveclojure.com/random-quote using (slurp "http://www.braveclojure.com/random-quote"). The futures should update an atom that refers to a total word count for all quotes. The function will take the number of quotes to download as an argument and return the atom’s final value. Keep in mind that you’ll need to ensure that all futures have finished before returning the atom’s final value.

This is my solution:

(def i (atom {}))(defn update-vals [map vals f](reduce #(update-in % [%2] f) map vals))(defn incifnil [x] (if (nil? x) 1 (inc x)))(require '[clojure.string :as str])(defn splitwords [s] (str/split s #"\W"))(defn word-counting [map s] (update-vals map (splitwords s) incifnil))(defn update-i [s] (swap! i word-counting s))(defn bring-quote [] (slurp "https://www.braveclojure.com/random-quote"))(defn future-creator [] (future (update-i (bring-quote))))(defn list_of_futures [n] (map (fn [_] (future-creator)) (range n)))(defn checkall-futures [future-list] (map deref future-list))(defn quote-word-count [n] (do                            (checkall-futures (list_of_futures n))                            @i))

But if I try to take the last value of atom i from the REPL I take an empty map.What am I doing wrong?


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images