Reputation: 41909
I'm looking for a standard library function that groups elements by equality.
Example:
f [1,2,3,1,2,3] == [ [1,1], [2,2], [3,3] ]
Composing group
and sort
does the job:
Prelude Data.List> group . sort $ [1,2,3,1,2,3]
[[1,1],[2,2],[3,3]]
But, is there a native function in Haskell's library that can perform the above work in a single function?
I looked at Data.List, but did not find such a function.
Upvotes: 0
Views: 127
Reputation: 2366
There is no such function in base
. However there is the discrimination
package. In Data.Discrimination
you will find the following function:
group :: Grouping a => [a] -> [[a]]
You don't have to write those Grouping
instances yourself, as there are default methods in place for types that have an instance for Generic
. For example:
{-# LANGUAGE DeriveGeneric #-}
import Data.Discrimination
data A = A deriving Generic
instance Grouping A
instance Sorting A -- Not necessary for what you are trying to do.
Upvotes: 3