Skip to content

Instantly share code, notes, and snippets.

@edennis
Created October 18, 2016 12:46
Show Gist options
  • Save edennis/720bebd8ffd80cf07a9a451ca60a5a65 to your computer and use it in GitHub Desktop.
Save edennis/720bebd8ffd80cf07a9a451ca60a5a65 to your computer and use it in GitHub Desktop.
defmodule ChainedStream do
# [#Function<59.77324385/2 in Stream.unfold/2>, #Function<59.77324385/2 in Stream.unfold/2>]
def test do
states = count(%{}, ["a", "b", "c"]) |> Enum.to_list
# [{%{"a" => 1}, ["b", "c"]}, {%{"a" => 1, "b" => 1},
# ["c"]}, {%{"a" => 1, "b" => 1, "c" => 1}, []}]
states |> Enum.at(-1) |> elem(0) |> count(["a", "b", "d"])
# [{%{"a" => 2, "b" => 1, "c" => 1}, ["b", "d"]},
# {%{"a" => 2, "b" => 2, "c" => 1}, ["d"]},
# {%{"a" => 2, "b" => 2, "c" => 1, "d" => 1}, []}]
end
def count(%{} = stats, things) do
Stream.unfold({stats, things}, &count_items/1)
end
def count_items({stats, []}), do: nil
def count_items({stats, [h | t] = items}) do
new_stats = Map.update(stats, h, 1, &(&1 + 1))
{{new_stats, t}, {new_stats, t}}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment