In elixir, Stream can be used to represent an infinite sequence. For example, 0, 1, 2, 3... can be represented as:
iex> s = Stream.iterate(0, & &1 + 1)
#Function<62.50989570/2 in Stream.unfold/2>
If we want to calculate the sum of every 5 numbers in this sequence, we can use the Stream.transform function:
iex> s1 = Stream.transform(s, {0, 0}, fn x, {sum, count} ->
...> if count == 5 do
...> {[sum], {x, 1}}
...> else
...> {[], {sum + x, count + 1}}
...> end
...> end)
#Function<60.50989570/2 in Stream.transform/3>
iex> Enum.take(s1, 10)
[10, 35, 60, 85, 110, 135, 160, 185, 210, 235]
It is the Stream version Enum.flat_map_reduce
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。