-
-
Save alco/1ecfe543f2caa4ca2441 to your computer and use it in GitHub Desktop.
This file contains 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 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 |
This file contains 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 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