Skip to content

Commit 25ffb4b

Browse files
author
José Valim
committed
Merge pull request #1652 from vanstee/stream-flat-map
Implement `Stream.flat_map/2`
2 parents e80dad1 + 8478db1 commit 25ffb4b

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

lib/elixir/lib/stream.ex

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,28 @@ defmodule Stream do
266266
end]
267267
end
268268

269+
@doc """
270+
Creates a stream that will apply the given function on enumeration and
271+
flatten the result.
272+
273+
## Examples
274+
275+
iex> stream = Stream.flat_map([1, 2, 3], fn(x) -> [x, x * 2] end)
276+
iex> Enum.to_list(stream)
277+
[1, 2, 2, 4, 3, 6]
278+
279+
"""
280+
281+
@spec flat_map(Enumerable.t, (element -> any)) :: t
282+
def flat_map(enumerable, f) do
283+
Lazy[enumerable: enumerable,
284+
fun: fn(f1) ->
285+
fn(entry, acc) ->
286+
Enumerable.reduce(f.(entry), acc, f1)
287+
end
288+
end]
289+
end
290+
269291
@doc """
270292
Creates a stream that will reject elements according to
271293
the given function on enumeration.

lib/elixir/test/elixir/stream_test.exs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,15 @@ defmodule StreamTest do
8686
assert Stream.map(nats, &(&1 * 2)) |> Enum.take(5) == [2,4,6,8,10]
8787
end
8888

89+
test :flat_map do
90+
stream = Stream.flat_map([1, 2, 3], &[&1, &1 * 2])
91+
assert is_lazy(stream)
92+
assert Enum.to_list(stream) == [1, 2, 2, 4, 3, 6]
93+
94+
nats = Stream.iterate(1, &(&1 + 1))
95+
assert Stream.flat_map(nats, &[&1, &1 * 2]) |> Enum.take(6) == [1, 2, 2, 4, 3, 6]
96+
end
97+
8998
test :reject do
9099
stream = Stream.reject([1,2,3], fn(x) -> rem(x, 2) == 0 end)
91100
assert is_lazy(stream)

0 commit comments

Comments
 (0)