Skip to content

Instantly share code, notes, and snippets.

@ehamberg
Created December 16, 2011 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehamberg/1485531 to your computer and use it in GitHub Desktop.
Save ehamberg/1485531 to your computer and use it in GitHub Desktop.
Solution for Programming Praxis, 6 Dec 2011 (http://programmingpraxis.com/2011/12/16/majority-voting/)
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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment