Adam R
Adam R

Reputation: 141

Haskell split tuple array where first elements are the same

I have a list in Haskell of a form similar to

[([], "str1"), ([], "str2"), ([1], "ser1")]

and I want to split this into separate lists of 2-tuples, where the first elements of each tuple are the same, like so

[([], "str1"), ([], "str2")]
[([1], "ser1")]

I''ve been eyeing Data.List.Split's splitWhen function, but I've been having trouble getting ghc to accept a predicate for it, since I gather it really wasn't meant to do that.

Upvotes: 0

Views: 345

Answers (1)

DNA
DNA

Reputation: 42597

I think you can just use groupBy:

> import Data.List
> import Data.Function

> let xs = [([], "str1"), ([], "str2"), ([1], "ser1")]

> groupBy ((==) `on` fst) xs

[[([],"str1"),([],"str2")], [([1],"ser1")]]

Upvotes: 5

Related Questions