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
I've added three functions:
groupAssoc
,groupAssocBy
andgroupAssocWith
.They all take lists in the form
List ( k, v )
and outputList ( k, List v )
.A group of pairs
( k₁, v₁ ) ... ( kᵢ, vᵢ )
in our input wherekᵢ = k₂ = ... = kᵢ
will appear in our output as( k₁, [ v₁, ..., vᵢ ] )
. The equality ingroupAssocBy
andgroupAssocWith
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:
gives
I'm sure the same could be done withEDIT: I've just seen gatherEqualsBy, I guess the use cases collide with this one :smile:groupWhile
, but I find easier to get my head aroundgroupAssoc
If there is interest I'll happily write some docs and other tests