Skip to content

Instantly share code, notes, and snippets.

@alco
Forked from knewter/word_stats_test.exs
Last active August 29, 2015 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alco/1ecfe543f2caa4ca2441 to your computer and use it in GitHub Desktop.
Save alco/1ecfe543f2caa4ca2441 to your computer and use it in GitHub Desktop.
defmodule Bag do
defstruct store: %{}
def new do
%Bag{}
end
def put(%Bag{store: store}, thing) do
%Bag{store: Map.update(store, thing, 1, &( &1 + 1))}
end
def to_map(%Bag{store: store}) do
store
end
end
defimpl Collectable, for: Bag do
def empty(_dict) do
Bag.new
end
def into(original) do
# not sure what this means, just copied the HashSet impl
{original, fn
bag, {:cont, x} -> Bag.put(bag, x)
bag, :done -> bag
_, :halt -> :ok
end}
end
end
defmodule WordStats do
def letter_frequency words do
words
|> Stream.flat_map(&String.graphemes/1)
|> Enum.into(Bag.new)
|> Bag.to_map
end
end
ExUnit.start
defmodule TaskPlaygroundTest do
use ExUnit.Case
test "the truth" do
assert 1 + 1 == 2
#words = File.read!("/usr/share/dict/words") |> String.split("\n")
words = [
"cat",
"bag"
]
assert %{"c" => 1, "a" => 2, "t" => 1, "b" => 1, "g" => 1} == WordStats.letter_frequency(words)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment