Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Word count koan
defmodule Words do
@doc """
Given a phrase can count the occurrences of each word in that phrase.
## Example
Words.count("olly olly in come free")
#=> #HashDict<[{"come",1},{"free",1},{"in",1},{"olly",2}]>
"""
def count(input) do
input |> String.downcase |> get_words |> count_word_occurances
end
defp get_words(input) do
Regex.scan(%r/\w+/, input)
end
defp count_word_occurances(words) do
Enum.reduce words, HashDict.new, function increase_word_count/2
end
defp increase_word_count(word,dict) do
HashDict.update dict, word, 1, &1+1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment