Stream.transform
transform
, go back to Stream module for more information.
Specs
transform(Enumerable.t(), acc, fun) :: Enumerable.t() when fun: (element(), acc -> {Enumerable.t(), acc} | {:halt, acc}), acc: any()
Transforms an existing stream.
It expects an accumulator and a function that receives each stream element
and an accumulator. It must return a tuple, where the first element is a new
stream (often a list) or the atom :halt
, and the second element is the
accumulator to be used by the next element, if any, in both cases.
Note: this function is equivalent to Enum.flat_map_reduce/3
, except this
function does not return the accumulator once the stream is processed.
Examples
Stream.transform/3
is useful as it can be used as the basis to implement
many of the functions defined in this module. For example, we can implement
Stream.take(enum, n)
as follows:
iex> enum = 1001..9999
iex> n = 3
iex> stream = Stream.transform(enum, 0, fn i, acc ->
...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc}
...> end)
iex> Enum.to_list(stream)
[1001, 1002, 1003]
Specs
transform(Enumerable.t(), (() -> acc), fun, (acc -> term())) :: Enumerable.t() when fun: (element(), acc -> {Enumerable.t(), acc} | {:halt, acc}), acc: any()
Transforms an existing stream with function-based start and finish.
The accumulator is only calculated when transformation starts. It also allows an after function to be given which is invoked when the stream halts or completes.
This function can be seen as a combination of Stream.resource/3
with
Stream.transform/3
.