Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard library solution to this Haskell problem?

I want to use Data.List.groupBy to group a list of tuples based on the equality of the snd element.
I could do this:

groupBy (\l r -> snd l == snd r) listOfTuples

But it strikes me as too much boilerplate in the comparison function -- especially because it could get a lot more messy if I were doing a more complicated comparison. I would like to do something like:

groupBy (comparing snd) listOfTuples

but the type signature of comparing is comparing :: (Ord a) => (b -> a) -> b -> b -> Ordering, so it doesn't compile in this example.
I could also do:

groupBy (\l r -> (comparing snd l r) == EQ) listOfTuples

But this is no better than the first try. Is there a standard-library solution to this problem, before I roll-my-own?

like image 267
Matt Fenwick Avatar asked Sep 19 '11 21:09

Matt Fenwick


People also ask

Does Haskell have a standard library?

rio 's tag line is "a standard library for Haskell." The idea is that the actual standard library for Haskell—the base package—leaves much to be desired. Very few real world applications use only base . There is a common set of functionality that is used by a large majority of applications.

What makes Haskell different from the languages that came before it?

Immutability and purity. Most programming languages out there default to mutability: a variable or field in a data structure can be changed at any time. Haskell is different in two ways: Values are immutable by default, and mutability must be explicitly indicated with a variable type.


1 Answers

groupBy ((==) `on` snd) listOfTuples

I think there used to be equating = on (==) in the standard libraries, though I can't seem to find it now.

like image 90
Daniel Wagner Avatar answered Oct 04 '22 18:10

Daniel Wagner