-- Voting algorithm example from chapter 7 of Programming in Haskell, -- Graham Hutton, Cambridge University Press, 2016. -- two voting algorithms to decide the winner in an election (1) First past the post (2) Alternative vote import Data.List ------------------------ -- First past the post - ------------------------ -- Rules -- - each person has a vote -- - the candidate with the largest amount of votes winn the election -- Example: -- The candidates are "Red", "Blue", "Green" votes :: [String] -- in this round the winner should be "Blue" votes = ["Red", "Blue", "Green", "Blue", "Blue", "Red"] ---------------------------------------- -- Generalise the idea and give the votes in a list and we count the number of occurrences of a candidate -- count "Blue" votes -- count :: Eq a => a -> [a] -> Int -- count x = -- This function remove duplicate values from a list, to obtain the names of the candidates -- rmdups votes rmdups :: Eq a => [a] -> [a] rmdups [] = [] rmdups (x:xs) = x : filter (/= x) (rmdups xs) -- result calculate the votes per candidate in order, it uses count and rmdups -- the function sort returns the pairs in ascending order -- result votes -- returns [(1,"Green"),(2,"Red"),(3,"Blue")] -- result :: Ord a => [a] -> [(Int, a)] -- result vs = sort -- returns the winner in the list, -- function last access the last element in a list -- function snd access the second element in a pair -- winner votes -- winner :: Ord a => [a] -> a -- winner = ------------------------ -- Alternative vote ---- ------------------------ -- Rules -- - each person can vote for nobody or for many candidates, -- listing them in their preference order on their ballot -- - to decide the winner, -- - first the empty votes are removed from the ballots -- - then the candidate with the smallest number of first choice is eliminated, -- this is repited until a winner is found ballots :: [[String]] -- Example: -- The candidates are "Red", "Blue", "Green" ballots = [["Red","Green"], ["Blue"], ["Green","Red","Blue"], ["Blue","Green","Red"], ["Green"]] -- "Red will be eliminated" -- ["Green"], -- ["Blue"], -- ["Green","Blue"], -- ["Blue","Green"], -- ["Green"]] -- "Blue" will be eliminated -- ["Green"], -- [], -- ["Green"], -- ["Green"], -- ["Green"]] -- so "Green" is the winner -- this function uses filter to remove empty ballots -- rmempty :: Eq a => [[a]] -> [[a]] -- rmempty = -- this function uses map and filter to eliminate a candidate from the ballots -- elim :: Eq a => a -> [[a]] -> [[a]] -- elim x = -- this function rank the 1st-choice candidates in increasing order -- rank ballots -- returns ["Red","Blue","Green"] -- rank :: Ord a => [[a]] -> [a] -- rank = map snd . result . map head -- this function implements the voting algorithm -- winner' ballots -- returns "Green" -- winner' :: Ord a => [[a]] -> a -- winner' bs = case rank (rmempty bs) of -- [c] -> -- (c:cs) ->