看個簡單的例子, 如何製造一個 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))