Skip to content

Instantly share code, notes, and snippets.

@ToJans
Created July 27, 2013 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ToJans/6093252 to your computer and use it in GitHub Desktop.
Save ToJans/6093252 to your computer and use it in GitHub Desktop.
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