開発環境
- OS X Mavericks - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs (Text Editor)
- Haskell (純粋関数型プログラミング言語)
- GHC (The Glasgow Haskell Compiler) (処理系)
- The Haskell Platform (インストール方法、モジュール等)
初めてのコンピュータサイエンス(Jennifer Campbell、Paul Gries、Jason Montojo、Greg Wilson(著)長尾 高弘(翻訳))の5章(リスト)、5.13(練習問題)、4から17をHaskellで解いてみる。
その他参考書籍
- プログラミングHaskell (オーム社) Graham Hutton(著) 山本 和彦(翻訳)
- Real World Haskell―実戦で学ぶ関数型言語プログラミング (オライリージャパン) Bryan O'Sullivan John Goerzen Don Stewart(著) 山下 伸夫 伊東 勝利 株式会社タイムインターメディア(翻訳)
5.13(練習問題)、4から17.
コード(BBEdit)
Sample.hs
{-# OPTIONS -Wall -Werror #-} main :: IO () main = do putStrLn $ "14. " ++ show alkalineEartnMetals putStrLn "15." mapM_ putStrLn $ map (\(a, b) -> show a ++ ' ':show b) alkalineEartnMetals putStrLn "16." mapM_ putStr $ map (\x -> show x ++ " ") $ concat alkalineEartnMetalsNestList putStrLn "" putStrLn "17." contents <- readFile "alkaline_metals.txt" putStrLn $ show $ getNumAndWeight contents alkalineEartnMetals :: [(Int, Double)] alkalineEartnMetals = [(4, 9.012), (12, 24.305), (20, 40.078), (38, 87.62), (56, 137.327), (88, 226.0)] alkalineEartnMetalsNestList :: [[Double]] alkalineEartnMetalsNestList = map (\(a, b) -> [(fromIntegral a) :: Double, b]) alkalineEartnMetals getNumAndWeight :: String -> [(Int, Double)] getNumAndWeight s = map twoStringListToIntAndDoublePairs $ map words $ lines s twoStringListToIntAndDoublePairs :: [String] -> (Int, Double) twoStringListToIntAndDoublePairs (a:b:[]) = (read a :: Int, read b :: Double) twoStringListToIntAndDoublePairs _ = (0, 0)
入出力結果(Terminal, runghc)
$ runghc Sample.hs 14. [(4,9.012),(12,24.305),(20,40.078),(38,87.62),(56,137.327),(88,226.0)] 15. 4 9.012 12 24.305 20 40.078 38 87.62 56 137.327 88 226.0 16. 4.0 9.012 12.0 24.305 20.0 40.078 38.0 87.62 56.0 137.327 88.0 226.0 17. [(4,9.012),(12,24.305),(20,40.078),(38,87.62),(56,137.327),(88,226.0)] $
{-# OPTIONS -Wall -Werror #-}を記述してるから、細かく型を指定(:: Double)しないと警告がいっぱい出た。慣れるまでは{-# OPTIONS -Wall -Werror #-}の記述を消さずに細かく型を指定していくことに。
0 コメント:
コメントを投稿