public
Created

Solution for Programming Praxis, 6 Dec 2011 (http://programmingpraxis.com/2011/12/16/majority-voting/)

  • Download Gist
majority.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import Data.Function (on)
import Data.List (group, sortBy, sort)
 
data Vote = A | B | C deriving (Eq, Show, Ord)
 
majority:: (Ord a, Eq a) => [a] -> Maybe a
majority votes = if length majority > (length votes `div` 2)
then Just (head majority)
else Nothing
where majority = (last . sortBy (compare `on` length) . group . sort) votes
 
main = do
let votes = [A, A, A, C, C, B, B, C, C, C, B, C, C]
print $ majority votes
let votes' = [A, B, C, A, B, C, A]
print $ majority votes'

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.