Specialised guard for checking of length of a list against a specified size

I wonder if it would be beneficial adding a guard along the line of length(list, n) which checks if a list has the length n without computing the entire length of the list if it happens to be bigger than n?
My primary motivation is that I can’t get my coworkers to not write guards in the form of length(list) == 1 or length(list) == 3 for example. And it seems to be a somewhat common pattern across my dependencies too.
Maybe the compiler could detect a call of the form length(ls) == n and transform that into a call to an optimized bif?
And would we need versions for other comparison operations?

This strikes me as something that should be done as a compiler optimisation.

From what I recall all guards checks, except for the length() one, are O(1), so there shouldn’t be anything else that would benefit from a optimisation like this.

1 Like

No, that would change the behavior for calls such as length([1, 2, 3, 4 | bad_tail) =:= 2.

1 Like