Group the list of tuples by their 1st element

Let's say I have a list of tuples consisting of [("ab", 1), ("ab", 2), ("ac", 3)]

Using a function groupwould split this list into a list of tuple lists:

[
  [("ab", 1)],
  [("ab", 2)],
  [("ac", 3)]
]

How would you group a tuple ignoring one of the indices so that they are grouped based on one of the elements:

[
  [("ab", 1), ("ab", 2)],
  [("ac", 3]
]

In this case, you need a function groupBy?

+4
source share
1 answer

Use the Data.List groupByfunction ( 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
+7
source

Source: https://habr.com/ru/post/1609223/


All Articles