frequencies & group-by in Clojure
Word counts with frequencies, then subway stops bucketed by group-by.
(require '[clojure.string :as str])
(def notice "the tide is out the boats are out the gulls are loud")
;; frequencies counts occurrences and returns a map of item to count
(def word-counts (frequencies (str/split notice #"\s+")))
(println (get word-counts "the") (get word-counts "out"))
(def stops [{:stop "Wharf" :line "A"} {:stop "Mill" :line "B"}
{:stop "Quay" :line "A"} {:stop "Ash" :line "C"}])
;; group-by builds a map from key fn result to a vector of the matches
(def by-line (group-by :line stops))
(println (map :stop (get by-line "A")))
;; group sizes are group-by plus a walk over the values
(println (reduce-kv (fn [m k v] (assoc m k (count v))) {} by-line))
How it works
(frequencies (str/split notice #"\s+"))counts each word into a map of item to count.(group-by :line stops)returns a map from line name to a vector of the matching stops.reduce-kvwalksby-lineand swaps each vector for itscount.
Keywords and builtins used here
assoccountdeffnfrequenciesgetmapprintlnrequire
The run, in numbers
- Lines
- 17
- Characters to type
- 679
- Tokens
- 120
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 103 seconds.
Step 1 of 3 in Seq toolkit, step 16 of 27 in Language basics.