Skip to content

Commit a835477

Browse files
author
José Valim
committed
Just iterate the next value if we are going to use it
1 parent 879651c commit a835477

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

lib/elixir/lib/stream.ex

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -224,21 +224,23 @@ defmodule Stream do
224224
Emit a sequence of values, starting with `start_value`. Successive
225225
values are generated by calling `next_fun` on the previous value.
226226
227-
228227
## Examples
229228
230-
iex> Stream.iterate(0, &1+1) |> Enum.take(5)
229+
iex> Stream.iterate(0, &1+1) |> Enum.take(5)
231230
[0,1,2,3,4]
232231
233232
"""
234233

235234
@spec iterate(element, (element -> element)) :: Lazy.t
236235
def iterate(start_value, next_fun) do
237-
do_iterate(start_value, next_fun, &1, &2)
236+
fn acc, fun ->
237+
do_iterate(start_value, next_fun, fun.(start_value, acc), fun)
238+
end
238239
end
239240

240-
defp do_iterate(start_value, next_fun, acc, fun) do
241-
do_iterate(next_fun.(start_value), next_fun, fun.(start_value, acc), fun)
241+
defp do_iterate(value, next_fun, acc, fun) do
242+
next = next_fun.(value)
243+
do_iterate(next, next_fun, fun.(next, acc), fun)
242244
end
243245

244246
@doc """

lib/elixir/test/elixir/stream_test.exs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ defmodule StreamTest do
6262
assert Enum.take(stream, 5) == [0,2,4,6,8]
6363
stream = Stream.iterate(5, &1+2)
6464
assert Enum.take(stream, 5) == [5,7,9,11,13]
65+
66+
# Only calculate values if needed
67+
stream = Stream.iterate("HELLO", raise(&1))
68+
assert Enum.take(stream, 1) == ["HELLO"]
6569
end
6670

6771
test :map do

0 commit comments

Comments
 (0)