Stream in Elixir

Stream is the lazy twin of Enum. The two modules answer the same function names, and the difference is when the work happens: an Enum call walks the data and returns a list at once, while a Stream call returns a description of the work, and nothing is computed until an Enum function asks for a value. A stream in Elixir is a recipe, not a result.

Nothing runs until Enum

The program below builds a stream with a print inside each step, then prints a line of its own, then asks for the list. The order of the lines is the proof: no step ran before the Enum.to_list/1 call:

lazy.exs

stream = [1, 2, 3] |> Stream.map(fn n -> IO.puts("map #{n}") n * 2 end) |> Stream.filter(fn n -> IO.puts("filter #{n}") n > 2 end) IO.puts("before Enum") IO.inspect(Enum.to_list(stream))

elixir lazy.exs

before Enum
map 1
filter 2
map 2
filter 4
map 3
filter 6
[4, 6]

The items also move one at a time: map 1, filter 2, then map 2 and so on. The stream does not map the whole list and filter the result; it feeds each item through the steps in turn, which is what makes a chain of streams one pass over the data.

A pipeline that walks the data once

The same chain with Enum builds a list after every step: a list of squares, then a filtered list, then the sum. With Stream there are no intermediate lists at all, and the sum is computed as the items arrive:

onepass.exs

sum = 1..10 |> Stream.map(&(&1 * &1)) |> Stream.filter(&(rem(&1, 2) == 0)) |> Enum.sum() IO.puts(sum)

elixir onepass.exs

220

For ten numbers the difference is invisible, and for a million rows it is the difference between one list in memory and a thousand. The last call of a stream pipeline is an Enum function, because something has to ask for the values; Stream alone never starts the work.

Sources that never end

A stream may describe an endless source, because it is never asked for all of it. Stream.iterate/2 builds the next value from the last one and Stream.cycle/1 repeats a list. Stream.take/2 says how many items the program wants, and the pipeline ends:

endless.exs

powers = Stream.iterate(1, &(&1 * 2)) IO.inspect(powers |> Stream.take(5) |> Enum.to_list()) IO.inspect(Stream.cycle([:a, :b]) |> Stream.take(4) |> Enum.to_list())

elixir endless.exs

[1, 2, 4, 8, 16]
[:a, :b, :a, :b]

Asking an endless stream for a list is the one call that never returns, and the program sits there rather than failing. Stream.take/2 belongs at the end of such a pipeline for that reason; lazy and eager takes the idea further.

When a Stream is worth it

A stream adds a small cost per item: the closure of each step and the calls between them. That cost is worth paying when the data is large, when the source is endless, or when the first answer is enough and the rest should never be computed. For a list of ten items that the program needs whole, an Enum call is shorter to read and faster to run, and the lesson before this one is the right tool.

The mistake: a Stream where a list is expected

A stream looks like a collection and is not one. is_list/1 answers false for it, and a function that wants a list, such as length/1 or the double plus, raises an ArgumentError that prints the whole recipe:

mistake.exs

stream = Stream.map([1, 2, 3], &(&1 * 2)) IO.puts(is_list(stream)) IO.puts(length(Enum.to_list(stream)))

elixir mistake.exs

false
3

The conversion is one call, Enum.to_list/1, and the rest of the program works on a plain list. A stream that is passed through a function and comes back is often a stream the program forgot to consume: the work has not happened, and the printed value is the description rather than the data.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. When does a Stream pipeline do its work?

    Answer

    When an Enum function asks for the values

    A stream is a description of the work, and an Enum call is what starts it.

  2. What does a chain of Stream calls avoid that the same chain of Enum calls builds?

    Answer

    The intermediate lists

    Each Enum step returns a list; the stream feeds each item through every step in one pass.

  3. What does Stream.iterate(1, &(&1 * 2)) describe?

    Answer

    An endless sequence 1, 2, 4, 8, ...

    The second argument builds each next value from the last one, with no end.

  4. Why does an endless stream not hang when Stream.take/2 is in the pipeline?

    Answer

    Because take stops asking for values after its count

    The pipeline pulls only the items the last step asks for, and take asks for a fixed number.

  5. What does this program print? IO.inspect(Stream.map([1, 2, 3], &(&1 * 2)) |> Enum.to_list())

    Answer

    [2, 4, 6]

    The Enum call consumes the stream and answers the list of doubled values.

  6. What does this program print? IO.puts(is_list(Stream.map([1, 2], &(&1 + 1))))

    Answer

    false

    A stream is a struct that describes work, not a list.

  7. What does this program print? IO.inspect(Stream.iterate(1, &(&1 * 2)) |> Stream.take(4) |> Enum.to_list())

    Answer

    [1, 2, 4, 8]

    The sequence starts at 1, and take asks for the first four values.

  8. What does this program print? IO.inspect(1..5 |> Stream.filter(&(rem(&1, 2) == 1)) |> Enum.to_list())

    Answer

    [1, 3, 5]

    The filter keeps the odd numbers of the range, in order.

  9. Which call consumes a stream and answers a list?

    Answer

    Enum.to_list/1

    Enum functions pull the values, and to_list is the one that collects all of them.

  10. When is an Enum call the better choice than a Stream?

    Answer

    When the list is small and the whole result is needed

    For a small input the stream adds cost per item and no benefit, and Enum reads shorter.

Article author: Arthur Isaev