Need to find the mode of a list of values (a map) in haskell

Viewed 110

for example I have [1,2,5,1,1,2], I have the function below,

card :: [Int] -> Map Int Int
card = Map.fromListWith (+) . (`zip`[1,1..])

that is able to give out this -> fromList [(1,3),(2,2),(5,1)] and now I have to use this function in order to get the mode from these tuples, I basically have to get the maximum value from the key-value pairs.

1 Answers

You can make use of maximumBy :: Foldable f => (a -> a -> Ordering) -> f a -> a to retrieve the maximum of the 2-tuples:

import Data.Function(on)
import Data.List(maximumBy)

maximum2Tuple :: Ord b => [(a, b)] -> a
maximum2Tuple = fst . maximumBy (compare `on` snd)

Now we can do this for a Map a Int by obtaining a list of 2-tuples that represent the key-value pairs. You thus can implment this as:

counterMode :: Map a Int -> a
counterMode = maximum2Tuple . …

where you need to fill in the … part as an exercise.

Related