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

Stream

看個簡單的例子, 如何製造一個 stream 源, 而且用 reduce_while 來提取數據.code

計算天然數集合中數字的和, 直到遇到不知足條件的數.it

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))
相關文章
相關標籤/搜索