On Thu, Jan 6, 2011 at 10:49 AM, new2clojure <miguel.arre...@gmail.com> wrote:
> I am trying to store into a map the frequency of each [a-z]+ word in a
> file. When I run this code in the repl the resulting dictionary is
> empty. How should I adapt my code to get this functionality right?.

Other people have offered up alternate solutions that should get you
pointed in the right direction but I wanted to highlight an important
issue which may be tripping you up, depending on your background:

> (def dictionary {})

This defines dictionary as an empty map. dictionary is immutable.

> (defn process-file [file-name]
>  (with-open
>    [rdr (BufferedReader. (FileReader. file-name))]
>    (doseq
>      [line (line-seq rdr)]
>      (reduce #(assoc %1 %2 (inc (get %1 %2 1))) dictionary (re-seq
> #"[a-z]+" (.toLowerCase line))))))

This does not change dictionary. The (assoc) call returns a new map.
The (reduce) call will ultimately return a new map (the result of
calling assoc several times).

The lack of side-effects / assignment can be quite hard to get your
head around if you're not used to functional programming.

As Ken noted, your (get) call needs to use 0 not one (since you always
(inc) it):

user=> (reduce #(assoc %1 %2 (inc (get %1 %2 1))) {} ["these" "are"
"some" "words" "with" "some" "words" "repeated"])
{"repeated" 2, "with" 2, "words" 3, "some" 3, "are" 2, "these" 2}

With (get %1 %2 0) we get the correct result:

user=> (reduce #(assoc %1 %2 (inc (get %1 %2 0))) {} ["these" "are"
"some" "words" "with" "some" "words" "repeated"])
{"repeated" 1, "with" 1, "words" 2, "some" 2, "are" 1, "these" 1}
-- 
Sean A Corfield -- (904) 302-SEAN
Railo Technologies, Inc. -- http://getrailo.com/
An Architect's View -- http://corfield.org/

"If you're not annoying somebody, you're not really alive."
-- Margaret Atwood

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