開発環境
- 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(著)長尾 高弘(翻訳))の4章(モジュール)、4.8(練習問題)、1、2を解いてみる。をHaskellで解いてみる。
その他参考書籍
- プログラミングHaskell (オーム社) Graham Hutton(著) 山本 和彦(翻訳)
- Real World Haskell―実戦で学ぶ関数型言語プログラミング (オライリージャパン) Bryan O'Sullivan John Goerzen Don Stewart(著) 山下 伸夫 伊東 勝利 株式会社タイムインターメディア(翻訳)
4.8(練習問題)、1、2.
コード(BBEdit)
Sample.hs
{-# OPTIONS -Wall -Werror #-} import qualified Data.Time.Calendar as Calendar import qualified Data.Time.Clock as Clock import qualified Data.Time.Format as Format import qualified System.Locale as Locale main :: IO () main = do putStrLn "1." putStrLn $ show (round (abs (-4.3) :: Double) :: Int) let a = sin (34.5 :: Double) if a < 0 then putStrLn $ show $ (-1) * (floor (abs a) :: Int) else putStrLn $ show $ (ceiling a :: Int) putStrLn "2." now <- Clock.getCurrentTime let day = Clock.utctDay now (year, _, _) = Calendar.toGregorian day putStrLn $ "次のうるう年: " ++ (show . firstLeap $ year) ++ "年" putStrLn $ "2000年から2050年までの間にあるうるう年の回数: " ++ show (length $ filter Calendar.isLeapYear [2000..2050]) ++ "回" let t = Calendar.fromGregorian 2016 7 29 putStrLn $ "2016/7/29 weekday: " ++ Format.formatTime Locale.defaultTimeLocale "%A" t firstLeap :: Integer -> Integer firstLeap a | Calendar.isLeapYear a = a | otherwise = firstLeap $ a + 1
入出力結果(Terminal, runghc)
$ runghc Sample.hs 1. 4 1 2. 次のうるう年: 2016年 2000年から2050年までの間にあるうるう年の回数: 13回 2016/7/29 weekday: Friday $
負の数で切り下げ(floor)、切り上げ(ceiling)、四捨五入、丸め(round)はHaskellでは上手くいかないみたい。(なのでabsで絶対値を取ってから計算してまた元の符号に応じて-1を掛けることに。)
{-# OPTIONS -Wall -Werror #-}を記述してるから、細かく型を指定(:: Double)しないと警告がいっぱい出た。慣れるまでは{-# OPTIONS -Wall -Werror #-}の記述を消さずに細かく型を指定していくことに。
0 コメント:
コメントを投稿