> (defn top-words-core [s] > (reduce #(assoc %1 %2 (inc (%1 %2 0))) {} > (re-seq #"\w+" > (.toLowerCase s))))
"maps are functions of their keys" means: user=> ({:a 1, :b 2, :c 3} :a) 1 Here we created a map {:a 1, :b 2, :c 3}, can then called it like a function with the argument :a and it finds the value associated with that key, which is 1. Maps and keys do this trick by delegating to get, which is a function that looks up stuff: user=> (get {:a 1, :b 2} :a) 1 get also accepts an optional third argument, which is returned if key is not found in map: user=> (get {:a 1, :b 2} :e 0) 0 But as we saw you don't need to call get, you can just call the map: user=> ({:a 1, :b 2, :c 3} :e 0) 0 Keys can be called in the same way (reverse of what we did above): user=> (:e {:a 1, :b 2} 99) 99 assoc stores a value in a map associated with a key: user=> (assoc {:a 1, :b 2} :b 3) {:a 1, :b 3} So this: #(assoc %1 %2 (inc (%1 %2 0))) Could be written as: (defn map-count [map key] (assoc map key (inc (get map key 0)))) ie: Given a map and a key, find the value associated with key in map, or 0 if not in the map, and increment it. Return a map that has the key associated with this value. (re-seq #"\w+" (.toLowerCase s)) turns the input string to lowercase then applys a regular expression to split it into a sequence of words. Which leaves us with: (reduce map-count {} sequence-of-words) {} empty map is supplied as the initial map and a whole sequence of keys (words) are fed in. reduce essentially does this: (map-count (map-count {} first-word) second-word) etc etc for every word ie: the result is used as input. Regards, Tim. --~--~---------~--~----~------------~-------~--~----~ 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 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 -~----------~----~----~----~------~----~------~--~---