Stream

看个简单的例子, 如何制造一个 stream 源, 并且用 reduce_while 来提取数据.

计算自然数集合中数字的和, 直到遇到不满足条件的数.

fn_start = fn -> 1 end
fn_next = fn                                  
  x -> {[x], x+1}                             
end
fn_after = fn _ -> :ok end
handler = fn limit ->
  fn x, acc -> 
    if limit.(x) do
      {:cont, x + acc}
    else
      {:halt, acc}
    end
  end
end

natures = Stream.resource(fn_start, fn_next, fn_after)
sum = fn res, limit ->
  res
  |> Enum.reduce_while(0, handler.(limit))
end

natures |> sum.(&(&1 <= 5))

Ljzn
399 声望102 粉丝

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