Skip to content

Commit

Permalink
Optimize Enum.flat_map/2 for filtering (#13793)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jean Klingler authored Aug 26, 2024
1 parent 27b894c commit a564c2e
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/elixir/lib/enum.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1266,13 +1266,16 @@ defmodule Enum do
def flat_map(enumerable, fun) do
reduce(enumerable, [], fn entry, acc ->
case fun.(entry) do
[] -> acc
list when is_list(list) -> [list | acc]
other -> [to_list(other) | acc]
end
end)
|> flat_reverse([])
end

# the first clause is an optimization
defp flat_reverse([[elem] | t], acc), do: flat_reverse(t, [elem | acc])
defp flat_reverse([h | t], acc), do: flat_reverse(t, h ++ acc)
defp flat_reverse([], acc), do: acc

Expand Down Expand Up @@ -4425,6 +4428,9 @@ defmodule Enum do

defp flat_map_list([head | tail], fun) do
case fun.(head) do
# the two first clauses are an optimization
[] -> flat_map_list(tail, fun)
[elem] -> [elem | flat_map_list(tail, fun)]
list when is_list(list) -> list ++ flat_map_list(tail, fun)
other -> to_list(other) ++ flat_map_list(tail, fun)
end
Expand Down

0 comments on commit a564c2e

Please sign in to comment.