Skip to content

Commit bcceccd

Browse files
author
José Valim
committed
Consider stream_lazy to always return the result, move nesting check to after reduce
1 parent b1cf5d9 commit bcceccd

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

lib/elixir/lib/stream.ex

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -97,35 +97,35 @@ defmodule Stream do
9797

9898
defimpl Enumerable, for: Lazy do
9999
def reduce(Lazy[] = lazy, acc, fun) do
100-
do_reduce(lazy, acc, fun)
100+
do_reduce(lazy, acc, fun, 0)
101101
end
102102

103103
def count(Lazy[] = lazy) do
104-
do_reduce(lazy, 0, fn _, acc -> acc + 1 end)
104+
do_reduce(lazy, 0, fn _, acc -> acc + 1 end, 0)
105105
end
106106

107107
def member?(Lazy[] = lazy, value) do
108108
do_reduce(lazy, false, fn(entry, _) ->
109109
if entry === value, do: throw({ :stream_lazy, true }), else: false
110-
end)
110+
end, 0)
111111
end
112112

113-
defp do_reduce(Lazy[enumerable: enumerable, fun: f1, acc: nil], acc, fun) do
114-
do_reduce(enumerable, acc, f1.(fun))
113+
defp do_reduce(Lazy[enumerable: enumerable, fun: f1, acc: nil], acc, fun, nesting) do
114+
do_reduce(enumerable, acc, f1.(fun), nesting)
115115
end
116116

117-
defp do_reduce(Lazy[enumerable: enumerable, fun: f1, acc: side], acc, fun) do
118-
case do_reduce(enumerable, { acc, side }, f1.(fun)) do
119-
{ acc, _ } -> acc
120-
acc -> acc
121-
end
117+
defp do_reduce(Lazy[enumerable: enumerable, fun: f1, acc: side], acc, fun, nesting) do
118+
do_reduce(enumerable, { acc, side }, f1.(fun), nesting + 1)
122119
end
123120

124-
defp do_reduce(enumerable, acc, fun) do
125-
Enumerable.reduce(enumerable, acc, fun)
121+
defp do_reduce(enumerable, acc, fun, nesting) do
122+
Enumerable.reduce(enumerable, acc, fun) |> remove_nesting(nesting)
126123
catch
127-
{ :stream_lazy, acc } -> acc
124+
{ :stream_lazy, res } -> res
128125
end
126+
127+
defp remove_nesting(acc, 0), do: acc
128+
defp remove_nesting(acc, nesting), do: remove_nesting(elem(acc, 0), nesting - 1)
129129
end
130130

131131
@type t :: Lazy.t | (acc, (element, acc -> acc) -> acc)
@@ -394,8 +394,8 @@ defmodule Stream do
394394
Lazy[enumerable: enumerable,
395395
fun: fn(f1) ->
396396
fn(entry, { acc, n }) ->
397-
acc = { f1.(entry, acc), n-1 }
398-
if n > 1, do: acc, else: throw { :stream_lazy, acc }
397+
res = f1.(entry, acc)
398+
if n > 1, do: { res, n-1 }, else: throw { :stream_lazy, res }
399399
end
400400
end,
401401
acc: n]
@@ -420,7 +420,7 @@ defmodule Stream do
420420
if f.(entry) do
421421
{ f1.(entry, acc), true }
422422
else
423-
throw { :stream_lazy, { acc, false } }
423+
throw { :stream_lazy, acc }
424424
end
425425
end
426426
end,

0 commit comments

Comments
 (0)