gleam-lang/gleam

Explicitly add list pattern when matching on non-empty list on the Erlang target

Open

#4,215 opened on Feb 4, 2025

View on GitHub
 (1 comment) (0 reactions) (0 assignees)Rust (960 forks)batch import
help wanted

Repository metrics

Stars
 (21,417 stars)
PR merge metrics
 (Avg merge 10d 19h) (69 merged PRs in 30d)

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.

Contributor guide