Stream
and Enum
both offer methods to use on enumerable data structures. The difference between them is that Enum is eager while Stream is lazy. Enum, being eager, produces a whole list of numbers after each operation in the script until the result is reached. Conversely, Stream, being lazy, creates a stream that represents a function without executing it straight away.
Streams are useful when working with huge, potentially infinite data sets. With large data sets, streams are more suitable as they do not fill up the memory with all the data at once, which Enum would do due to its intermediate lists.
range = 1..1_000_000stream = Stream.map(range, &(&1 * 3))IO.puts Enum.sum(stream)
Streams can also be used to produce infinite lists. These lists are not actually infinitely long, but functions can be applied to utilize only the amount of elements needed. Following is an example:
stream = Stream.cycle([1, 2, 3, 4, 5])IO.inspect Enum.take(stream, 15)
The
cycle
function creates an infinite stream of a list and thetake
function takes a specified number of elements from the stream.
RELATED TAGS