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
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)]]
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