gleam-lang/gleam
View on GitHubExplicitly add list pattern when matching on non-empty list on the Erlang target
Open
#4,215 opened on Feb 4, 2025
help wanted
Description
From Erlang's efficiency guide:
Don't:
map_pairs1(_Map, [], Ys) -> Ys;
map_pairs1(_Map, Xs, []) -> Xs;
map_pairs1(Map, [X|Xs], [Y|Ys]) -> todo.
Do:
map_pairs2(_Map, [], Ys) -> Ys;
map_pairs2(_Map, [_|_]=Xs, [] ) -> Xs;
map_pairs2(Map, [X|Xs], [Y|Ys]) -> todo.
In the second example, since Xs can no longer match with anything, the compiler is free to reorder the branches and make it as efficient as possible. I wonder if the Gleam compiler could emit code that plays nicely with this when it can tell you're matching on a non-empty list.