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