Created
September 26, 2013 01:35
-
-
Save quelgar/6708683 to your computer and use it in GitHub Desktop.
Find the most frequently occurring item that occurs more than once. Idea from http://skipoleschris.blogspot.com.au/2010/11/functional-programming-challenge-most.html
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 qualified Data.Map as Map | |
-- Find the most frequently occurring item that occurs more than once | |
-- Idea from http://skipoleschris.blogspot.com.au/2010/11/functional-programming-challenge-most.html | |
most :: Ord a => [a] -> Maybe a | |
most xs = fst $ foldl most' (Nothing, Map.empty) xs where | |
most' (winning, seen) x = (winning', seen') where | |
winning' = if count > winningCount then Just x else winning | |
seen' = Map.alter incSeen x seen | |
count = seen' Map.! x | |
winningCount = maybe 0 ((Map.!) seen) winning | |
incSeen i = Just $ maybe 0 ((+) 1) i | |
test1 = ["a", "b", "c", "a", "b", "a"] | |
test2 = ["a", "b", "c"] | |
test3 = ["a", "b", "a", "b"] | |
test4 = ["b", "a", "b", "a"] | |
test5 = [] :: [String] | |
test6 = [1, 2, 3, 4, 2, 3, 3, 3, 2] | |
toText :: Show a => Maybe a -> String | |
toText = maybe "None" show | |
mostText :: (Ord a, Show a) => [a] -> String | |
mostText = toText . most | |
main = do | |
putStrLn $ mostText test1 | |
putStrLn $ mostText test2 | |
putStrLn $ mostText test3 | |
putStrLn $ mostText test4 | |
putStrLn $ mostText test5 | |
putStrLn $ mostText test6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment