2013年12月21日土曜日

開発環境

初めてのコンピュータサイエンス(Jennifer CampbellPaul GriesJason MontojoGreg Wilson(著)長尾 高弘(翻訳))の12章(各種ツール)、12.7(練習問題)、12-17.をHaskellで解いてみる。

その他参考書籍

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]

入出力結果(Terminal, runghc)

$ runghc Sample.hs
[1,2,3,4,5,6,7,8,9,10]
平均: 5.5
[5,1,4,2,3]
中央値: 3.0
[5,1,4,2,3,6]
中央値: 3.5
[0,1,0,3,2,4,1]
最頻値: [0,1]
$

慣れるまでは{-# OPTIONS -Wall -Werror #-}の記述を消さずに細かく型を指定していくことに。

0 コメント:

コメントを投稿

Comments on Google+: