You are looking for a slightly higher level function called on
:
> import Data.Function
> :t on
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
Well how do I use that? Like this!
> :t ( (==) `on` snd )
( (==) `on` snd ) :: Eq b => (a, b) -> (a, b) -> Bool
So that means we want:
> groupBy ( (==) `on` snd) [ (1,3), (23,9), (42,9), (1,3), (48, 3), (18,18)]
[[(1,3)],[(23,9),(42,9)],[(1,3),(48,3)],[(18,18)]]
Yay!
EDIT:
I'd like to note how comparing
relates to on
. It is just a specialized use of on
!
> :t comparing
comparing :: Ord a => (b -> a) -> b -> b -> Ordering
> :t (compare `on`)
(compare `on`) :: Ord b => (a -> b) -> a -> a -> Ordering
(notice the type variables are swapped, but you can see the types are identical)