Lists:foldlwhile & lists:groupby

Taking inspiration from Elixir I guess that in Erlang two main functions are missing:
lists:foldlwhile : Introducing lists:foldlwhile by meox · Pull Request #5583 · erlang/otp · GitHub
lists:groupby : Add lists:groupby by meox · Pull Request #5588 · erlang/otp · GitHub

The foldlwhile is the equivalent of Enum.reduce_while and permits to stop the a foldl as soon as some condition is detected.

The groupby is the equivalent of Enum.group_by and permits to groups element using a discriminator (specified using a lambda function). As a result we have a map.

I hope that these functions will be taken in consideration from the OTP maintainers because I already implemented several times in my day to day programming.

10 Likes

These will be useful.

Q: Why not return a proplist for groupby? Would that not be more consistent for a function in the lists module?

3 Likes

I don’t have a strong opinion on that. I choose a map because I guess that the proplists is used to pass some options to a function and not as a return value

3 Likes

doc & tests updated

2 Likes

I can definitely see the use case for foldlwhile. It’s a no-brainer to me that I’d use it in place of hand-crafted recursive functions or potentially inefficient whole list operations.

For groupby I’d need to see some examples of use cases (not being an Elixir dev, the comparison to Enum.group_by, whilst interesting, is only indirectly relevant). I’m also wary that having its output as a map is contrary to existing lists functions. Just throwing it out there as a random idea, perhaps the functionality should live in the maps module?

2 Likes

An example of group_by: imagine to have a list of objects and you want to validate those object and if all are valid you want to store in an ETS table but grouped by a name or a property (that can be part of the object or derived from it). In this case having a lists:groupby is particular useful

2 Likes