On 14 Jun 2010, at 12:37, Steve Purcell wrote:
> On 14 Jun 2010, at 01:14, Todd wrote:
>
>> I'm attempting to write a simple histogram function:
>>
>> <code>
>> (defn create-histogram [f]
>> (let
>> [words (read-lines f)
>> histo {}]
>> (doall
>> (map
>> (fn [w] (assoc histo w (+1 (get histo w 0))))
>> words))
>> histo))
>>
>> (create-histogram "./testwords")
>> </code>
>>
>> The input, 'f', is expected to be a file of words, as you'd get from
>> '/usr/share/dict/words'.
>>
>> I don't see how to accumulate the results in the map, 'histo'. This is
>> really a question of how does one map a function to a collection and
>> accumulate the results...
>
>
> "reduce" is the canonical way to combine a number of input values into a
> single result. Here you're constructing a histogram from a sequence of words,
> so try something like the following:
>
> (defn create-histogram [f]
> (reduce (fn [hist word]
> (merge-with + hist {word 1}))
> {}
> (read-lines f)))
Or even:
(defn create-histogram [f]
(apply merge-with + (map array-map (read-lines f) (repeat 1))))
In any case, your original code could be re-written to use 'reduce' like this:
(defn create-histogram [f]
(let [words (read-lines f)]
(reduce (fn [histo w] (assoc histo w (inc (get histo w 0))))
{}
words)))
-Steve
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en