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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With