Reputation: 1183
Say I have a tuple list that consists of [("ab", 1), ("ab", 2), ("ac", 3)]
Using the group
function would split this list into a list of lists of tuples like so:
[
[("ab", 1)],
[("ab", 2)],
[("ac", 3)]
]
How would you group the tuple ignoring one of the indices so that they'd be grouped based on one of the elements:
[
[("ab", 1), ("ab", 2)],
[("ac", 3]
]
Would the groupBy
function be needed in this case?
Upvotes: 8
Views: 3687
Reputation: 16412
Use Data.List
groupBy
function (docs):
Prelude> import Data.List
Prelude Data.List> let xs = [("ab", 1), ("ab", 2), ("ac", 3)]
Prelude Data.List> groupBy (\a b -> fst a == fst b) xs
[[("ab",1),("ab",2)],[("ac",3)]]
or as suggested by @dfeuer:
...
import Data.Function
groupBy ((==) `on` fst) xs
Upvotes: 9