Elixir – Streams

  • Post author:
  • Post category:Elixir
  • Post comments:1 Comment
Elixir - Streams

This topic is about Elixir – Streams.

Many functions expect an enumerable and return a list back. It means, while performing multiple operations with Enum, each operation is going to generate an intermediate list until we reach the result.

Streams support lazy operations as opposed to eager operations by enums. In short, streams are lazy, composable enumerables. What this means is Streams do not perform an operation unless it is absolutely needed. Let us consider an example to understand this −

odd? = &(rem(&1, 2) != 0)
res = 1..100_000 |> Stream.map(&(&1 * 3)) |> Stream.filter(odd?) |> Enum.sum
IO.puts(res)

When the above program is run, it produces the following result −

7500000000

In the example given above, 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. It has not yet evaluated this representation. Instead of generating intermediate lists, streams build a series of computations that are invoked only when we pass the underlying stream to the Enum module. Streams are useful when working with large, possibly infinite, collections.

Streams and enums have many functions in common. Streams mainly provide the same functions provided by the Enum module which generated Lists as their return values after performing computations on input enumerables. Some of them are listed in the following table −

Sr.No.Function and its Description
1chunk(enum, n, step, leftover \\ nil)Streams the enumerable in chunks, containing n items each, where each new chunk starts step elements into the enumerable.
2concat(enumerables)Creates a stream that enumerates each enumerable in an enumerable.
3each(enum, fun)Executes the given function for each item.
4filter(enum, fun)Creates a stream that filters elements according to the given function on enumeration.
5map(enum, fun)Creates a stream that will apply the given function on enumeration.
6drop(enum, n)Lazily drops the next n items from the enumerable.

In this topic is we learned about Elixir – Streams. To know more, Click Here.

This Post Has One Comment

Leave a Reply