Skip to content

Instantly share code, notes, and snippets.

@stockwellb
Created June 6, 2016 00:52
Show Gist options
  • Save stockwellb/cf1feedd7a27bf064c2aab7373d3c238 to your computer and use it in GitHub Desktop.
Save stockwellb/cf1feedd7a27bf064c2aab7373d3c238 to your computer and use it in GitHub Desktop.
Word count in Elixir
defmodule WordCount do
def count(phrase) do
String.split(phrase)
|> Enum.reduce(%{}, fn(word, map) ->
Map.update(map, word, 1, &(&1 + 1))
end)
|> Enum.to_list()
end
end
ExUnit.start
defmodule WordCountTest do
use ExUnit.Case, async: true
test "no words no count" do
result = WordCount.count("")
assert [] == result
end
test "three words 3 count" do
[{_,count}|_] = WordCount.count("hello hello hello")
assert count == 3
end
test "multiple counts" do
result = WordCount.count("this is fun this is fun this is fun")
assert length(result) == 3
[{_, count}| _] = result
assert count == 3
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment