Skip to content

Commit

Permalink
Optimize lists:flatmap/2 for filtering
Browse files Browse the repository at this point in the history
  • Loading branch information
sabiwara committed Aug 27, 2024
1 parent 1afaa45 commit 29bb2b4
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/stdlib/src/lists.erl
Original file line number Diff line number Diff line change
Expand Up @@ -2113,7 +2113,12 @@ flatmap(F, List) when is_function(F, 1) ->
flatmap_1(F, List).

flatmap_1(F, [Hd | Tail]) ->
F(Hd) ++ flatmap_1(F, Tail);
case F(Hd) of
%% The two first clauses are an optimization.
[] -> flatmap_1(F, Tail);
[Elem] -> [Elem | flatmap_1(F, Tail)];
List -> List ++ flatmap_1(F, Tail)
end;
flatmap_1(_F, []) ->
[].

Expand Down

0 comments on commit 29bb2b4

Please sign in to comment.