Created
July 27, 2013 01:12
-
-
Save ToJans/6093252 to your computer and use it in GitHub Desktop.
Word count koan
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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