PassiveSupport.Stream.with_memo
You're seeing just the function
with_memo
, go back to PassiveSupport.Stream module for more information.
Link to this function
with_memo(enum, accumulator, fun, evaluate_first \\ true)
Specs
with_memo( Enumerable.t(), any(), (Stream.element(), Stream.acc() -> Stream.acc()), boolean() ) :: Enumerable.t()
Processes an item while iterating through the provided stream
PassiveSupport.Stream.with_memo/3
attaches an arbitrary accumulator
acc
to the provided enum
, and transforms it in relation to each
successive item in the enumerable according to the return of fun.(item, acc)
.
Think of it like Stream.with_index/2
, but with the abstracted versatility
of Enum.reduce/3
.
In fact, implementing Stream.with_index/2
is possible with PassiveSupport.Stream.with_memo/3
iex> with_index = fn enum ->
...> with_memo(enum, -1, fn _el, ix -> ix+1 end)
...> end
iex> String.graphemes("hi world!") |> with_index.() |> Enum.to_list
[{"h", 0}, {"i", 1}, {" ", 2},
{"w", 3}, {"o", 4}, {"r", 5}, {"l", 6}, {"d", 7}, {"!", 8}
]
By passing false
as a fourth argument, evaluate_first
, you can return
accumulator
in the state it was in prior to fun
being called.
iex> with_memo(?a..?c, "", fn char, string -> string <> to_string([char]) end) |> Enum.to_list
[
{97, "a"},
{98, "ab"},
{99, "abc"}
]
iex> with_memo(?a..?c, "", fn char, string -> string <> to_string([char]) end, false) |> Enum.to_list
[
{97, ""},
{98, "a"},
{99, "ab"}
]