elm-community / list-extra

Convenience functions for working with List.
http://package.elm-lang.org/packages/elm-community/list-extra/latest
MIT License
135 stars 58 forks source link

Add group function for association lists #146

Closed emilianobovetti closed 3 years ago

emilianobovetti commented 3 years ago

I've added three functions: groupAssoc, groupAssocBy and groupAssocWith.

They all take lists in the form List ( k, v ) and output List ( k, List v ).

A group of pairs ( k₁, v₁ ) ... ( kᵢ, vᵢ ) in our input where kᵢ = k₂ = ... = kᵢ will appear in our output as ( k₁, [ v₁, ..., vᵢ ] ). The equality in groupAssocBy and groupAssocWith can be defined as a user function just like in List.sortBy and List.sortWith.

The use case is... well group things of course!

For example:

[ { name = "bob", age = 20 }
, { name = "alice", age = 25 }
, { name = "bob", age = 32 }
]
    |> List.map (\p -> ( p.name, p ))
    |> List.Extra.groupAssoc

gives

[ ( "alice", [ { age = 25, name = "alice" } ] )
, ( "bob", [ { age = 20, name = "bob" }, { age = 32, name = "bob" } ] )
]

I'm sure the same could be done with groupWhile, but I find easier to get my head around groupAssoc EDIT: I've just seen gatherEqualsBy, I guess the use cases collide with this one :smile:

If there is interest I'll happily write some docs and other tests

Chadtech commented 3 years ago

Yeah I appreciate you making the PR, but it does seem like the use case is covered by gatherEqualsBy

emilianobovetti commented 3 years ago

Feel free to close!