Orange Receptacle
Orange Receptacle

Reputation: 1183

Group a list of tuples by their 1st element

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

Answers (1)

yǝsʞǝla
yǝsʞǝla

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

Related Questions