[elixir! 51] Stream.resource 和 Enum.reduce_while 的用法

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))

你可能感兴趣的:(elixir)