Created
December 16, 2011 10:28
-
-
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/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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