Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 916
Orange Receptacle Avatar asked Sep 28 '15 00:09

Orange Receptacle


1 Answers

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
like image 189
yǝsʞǝla Avatar answered Nov 10 '22 14:11

yǝsʞǝla