Home » Elixir » Elixir Streams
Welcome to a tutorial on Elixir. Here you will learn about Streams in Elixir.
Most functions expect an enumerable and return a list, meaning that, while performing multiple operations with Enum, each operation will generate an intermediate list until we reach the result.
Lazy operations are supported by Streams as opposed to eager operations by enums. However, streams are in fact lazy, composable enumerables. It means that Streams do not perform an operation unless it is absolutely needed. Check out the example below to understand this concept.
odd? = &(rem(&1, 2) != 0)
res = 1..100_000 |> Stream.map(&(&1 * 3)) |> Stream.filter(odd?) |> Enum.sum
IO.puts(res)
The output is:
7500000000
In the above code, 1..100_000 |> Stream.map(&(&1 * 3)) returns a data type, an actual stream, that represents the map computation over the range 1..100_000. Although, it has not yet evaluated this representation. Rather than generating intermediate lists, streams build a series of computations that are invoked only when the underlying stream is passed to the Enum module.
However, Streams are useful when working with large, possibly infinite, collections. Also, Streams and enums have many functions in common; Streams typically provide the same functions provided by the Enum module which generated Lists as their return values after performing computations on input enumerable. The table below highlights some of these functions.
Sr.No. | Function and its Description |
1 | chunk(enum, n, step, leftover nil): This is used to Stream the enumerable in chunks, containing n items each, where each new chunk starts step elements into the enumerable. |
2 | concat(enumerables): This typically creates a stream that enumerates each enumerable in an enumerable. |
3 | each(enum, fun): It executes the given function for each item. |
4 | filter(enum, fun): It creates a stream that filters elements according to the given function on enumeration. |
5 | map(enum, fun): It creates a stream that will apply the given function on enumeration. |
6 | drop(enum, n): This lazily drops the next n items from the enumerable. |