Skip to content

Commit 23a4fc6

Browse files
author
José Valim
committed
Add Stream.each/2
1 parent 575e0b9 commit 23a4fc6

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

lib/elixir/lib/stream.ex

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,31 @@ defmodule Stream do
182182
lazy enum, true, fn(f1) -> R.drop_while(fun, f1) end
183183
end
184184

185+
@doc """
186+
Execute the given function for each item.
187+
188+
Useful for adding side effects (like printing) to a stream.
189+
190+
## Examples
191+
192+
iex> stream = Stream.each([1, 2, 3], fn(x) -> IO.puts x end)
193+
iex> Enum.to_list(stream)
194+
1
195+
2
196+
3
197+
[1,2,3]
198+
199+
"""
200+
@spec each(Enumerable.t, (element -> term)) :: Enumerable.t
201+
def each(enum, fun) do
202+
lazy enum, fn(f1) ->
203+
fn(x, acc) ->
204+
fun.(x)
205+
f1.(x, acc)
206+
end
207+
end
208+
end
209+
185210
@doc """
186211
Creates a stream that will filter elements according to
187212
the given function on enumeration.

lib/elixir/test/elixir/stream_test.exs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,18 @@ defmodule StreamTest do
105105
assert Stream.drop_while(nats, &(&1 <= 5)) |> Enum.take(5) == [6,7,8,9,10]
106106
end
107107

108+
test "each" do
109+
Process.put(:stream_each, [])
110+
111+
stream = Stream.each([1,2,3], fn x ->
112+
Process.put(:stream_each, [x|Process.get(:stream_each)])
113+
end)
114+
115+
assert is_lazy(stream)
116+
assert Enum.to_list(stream) == [1,2,3]
117+
assert Process.get(:stream_each) == [3,2,1]
118+
end
119+
108120
test "filter" do
109121
stream = Stream.filter([1,2,3], fn(x) -> rem(x, 2) == 0 end)
110122
assert is_lazy(stream)

0 commit comments

Comments
 (0)