Anonymous user
Averages/Mode: Difference between revisions
→{{header|Haskell}}
(Added Scala) |
|||
Line 345:
=={{header|Haskell}}==
<lang haskell>import Prelude (foldr, maximum, (==), (+))
import Data.Map (insertWith', empty, filter, elems, keys)
mode :: (Ord a) => [a] -> [a]
mode xs = keys (filter (== maximum (elems counts)) counts)
where counts = foldr (\x -> insertWith' (+) x 1) empty xs</lang>
Line 362:
<lang haskell>import Data.List (group, sort)
mode :: (Ord a) => [a] -> [a]
mode xs = map fst $ filter ((==best).snd) counts
where counts = map (\l -> (head l, length l)) . group . sort $ xs
best = maximum (map snd counts)</lang>
Another version that does not require an orderable type:
<lang haskell>import Data.List (partition)
mode :: (Eq a) => [a] -> [a]
mode = snd . maxCounts
where maxCounts :: (Eq a) => [a] -> (Int, [a])
maxCounts [] = (0,[])
maxCounts l@(x:_) | length ys > n = (length ys, [x])
| length ys < n = (n, maxs)
| otherwise = (n, x:maxs)
where (ys,zs) = partition (== x) l
(n,maxs) = maxCounts zs</lang>
=={{header|J}}==
|