## 2013年12月21日土曜日

### Haskell - List(算術的平均値, 中央値, 最頻値を返す関数, Data.Mapモジュール)

その他参考書籍

12.7(練習問題)、12-17.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}
import qualified Data.List as L
import qualified Data.Map as Map

main :: IO ()
main = do
print nums1
putStrLn \$ "平均: " ++ (show \$ mean \$ map fromIntegral nums1)
print nums2
putStrLn \$ "中央値: " ++ (show \$ median \$ map fromIntegral nums2)
print nums3
putStrLn \$ "中央値: " ++ (show \$ median\$ map fromIntegral nums3)
print nums4
putStrLn \$ "最頻値: " ++ (show \$ mode nums4)

mean :: [Double] -> Double
mean ns = (sum ns) / (fromIntegral \$ length ns)

median :: [Double] -> Double
median [] = 0
median ns =
let l = length ns
n = div l 2
ms = L.sort ns
in if mod l 2 == 0 then
((ms !! (n - 1)) + (ms !! n)) / 2
else
(ms !! n)

mode :: [Int] -> [Int]
mode [] = []
mode ns =
let l = Map.fromListWith (\n m -> n + m) \$ map (\x -> (x, (1::Double))) ns
a = foldr1 (\x acc -> if x > acc then x else acc) \$ Map.elems l
in Map.keys \$ Map.filter (==a) l

f :: Maybe a -> a
f Nothing = undefined
f (Just a) = a

nums1 :: [Int]
nums1 = [1..10]

nums2 :: [Int]
nums2 = [5, 1, 4, 2, 3]

nums3 :: [Int]
nums3 = [5, 1, 4, 2, 3, 6]

nums4 :: [Int]
nums4 = [0, 1, 0, 3, 2, 4, 1]

\$ runghc Sample.hs
[1,2,3,4,5,6,7,8,9,10]

[5,1,4,2,3]

[5,1,4,2,3,6]

[0,1,0,3,2,4,1]

\$