Skip to content

Instantly share code, notes, and snippets.

@rozap
Created January 24, 2017 20:21
Show Gist options
  • Save rozap/ca6d431f801d81c629554d502046cc38 to your computer and use it in GitHub Desktop.
Save rozap/ca6d431f801d81c629554d502046cc38 to your computer and use it in GitHub Desktop.
defmodule Advance do
defp advance_by(stream, count) do
Enumerable.reduce(stream, count, fn
x, {acc, 1} -> {:suspend, {[x | acc], 0}}
x, {acc, counter} -> {:cont, {[x | acc], counter - 1}}
end)
end
defp continue(cont, by) do
{_, {head, _}, cont} = cont.({:cont, {[], by}})
{Enum.reverse(head), fn -> continue(cont, by) end}
end
def advance(stream, by) do
continuation = &advance_by(stream, &1)
continue(continuation, by)
end
def advance(stream), do: advance(stream, 1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment