Monday, January 30, 2017

Elixir - Streams

All the functions in the Enum module are eager. Many functions expect an enumerable and return a list back. This means that when performing multiple operations with Enum, each operation is going to generate an intermediate list until we reach the result. We saw an example for the same in the previous chapter.

Ok so why was this discussed here? Actually streams support lazy operations as opposed to eager operations by enums. In short, Streams are lazy, composable enumerables. What this means is Streams dont perform an operation unless it is absolutely needed. Let us take 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 running above program, it produces following result:
7500000000
In the example 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 provides the same functions provided by the Enum module which generated Lists as their return values after perfoming computations on input enumerables. Some of them are:
S. No. Function and its Description
1 chunk(enum, n, step, leftover \\ nil)
Streams the enumerable in chunks, containing n items each, where each new chunk starts step elements into the enumerable.
2 concat(enumerables)
Creates a stream that enumerates each enumerable in an enumerable
3 each(enum, fun)
Executes the given function for each item
4 filter(enum, fun)
Creates a stream that filters elements according to the given function on enumeration
5 map(enum, fun)
Creates a stream that will apply the given function on enumeration
6 drop(enum, n)
Lazily drops the next n items from the enumerable

No comments:

Post a Comment