Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell grouping list elements by fst

I'm trying to write a function

group::[(Int, Int)]->[[(Int, Int)]]

that would group elements of a list of tuples into subgroups dependant on the first coordinate, ie:

group [(1,1),(1,2),(2,1),(2,2),(2,3)]

should result in

[[(1,1),(1,2)],[(2,1),(2,2),(2,3)]]

I'd imagine list comprehension is the way, but I'm a bit stuck.. Could someone provide an advice/solution?

PS the function could also take as an argument the maximum the first coordinate can take, if that would be of any help

like image 269
Marcin Avatar asked Feb 10 '23 23:02

Marcin


1 Answers

You can do this using groupBy

λ: groupBy (\x y -> fst x == fst y) [(1,1),(1,2),(2,1),(2,2),(2,3)]
[[(1,1),(1,2)],[(2,1),(2,2),(2,3)]]

The on function is useful here to shorten the code a bit without obfuscating it:

λ: groupBy ((==) `on` fst) [(1,1),(1,2),(2,1),(2,2),(2,3)]
[[(1,1),(1,2)],[(2,1),(2,2),(2,3)]]
like image 141
Frerich Raabe Avatar answered Feb 19 '23 18:02

Frerich Raabe