1

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


Ljzn
399 声望102 粉丝

网络安全;函数式编程;数字货币;人工智能