Skip to content

Instantly share code, notes, and snippets.

@scudelletti
Last active August 29, 2015 14:16
Show Gist options
  • Save scudelletti/71ae40894947fcf07a81 to your computer and use it in GitHub Desktop.
Save scudelletti/71ae40894947fcf07a81 to your computer and use it in GitHub Desktop.
Count Words using Clojure - Loop and Map Reduce Way
(defn split-words
[phrase]
(clojure.string/split phrase #"\s"))
(defn count-words
[phrase word]
(let [words (split-words (clojure.string/lower-case phrase))
lower-case-word (clojure.string/lower-case word)]
(loop [head (first words)
tail (rest words)
sum 0]
(if (nil? head)
sum
(if (= head lower-case-word)
(recur (first tail) (rest tail) (+ sum 1))
(recur (first tail) (rest tail) sum))))))
(count-words "Era uma Vez Bem Uma" "Uma")
(defn split-words
[phrase]
(clojure.string/split phrase #"\s"))
(defn word-to-number
[original, word]
(if (= word original)
1
0))
(defn count-words
[phrase word]
(let [words (split-words (clojure.string/lower-case phrase))
lower-case-word (clojure.string/lower-case word)]
(reduce + (map (partial word-to-number lower-case-word) words))))
(count-words "Era uma Vez Bem Uma" "Uma")
(defn split-words
[phrase]
(clojure.string/split phrase #"\s"))
(defn word-to-number
[original word]
(if (= word original)
1
0))
(defn count-items
[items original]
(let [head (first items)
tail (rest items)
match (word-to-number head, original)]
(if (empty? tail)
match
(+ match (count-items tail original)))))
(defn count-words
[phrase word]
(let [words (split-words (clojure.string/lower-case phrase))
lower-case-word (clojure.string/lower-case word)]
(count-items words lower-case-word)))
(count-words "Era uma Vez Bem Uma" "Uma")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment