Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

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

View majority.hs
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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.