開発環境
- 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(著)長尾 高弘(翻訳))の12章(各種ツール)、12.7(練習問題)、12-15.をHaskellで解いてみる。
その他参考書籍
- プログラミングHaskell (オーム社) Graham Hutton(著) 山本 和彦(翻訳)
- Real World Haskell―実戦で学ぶ関数型言語プログラミング (オライリージャパン) Bryan O'Sullivan John Goerzen Don Stewart(著) 山下 伸夫 伊東 勝利 株式会社タイムインターメディア(翻訳)
12.7(練習問題)、12-15.
コード(BBEdit)
Sample.hs
{-# OPTIONS -Wall -Werror #-} main :: IO () main = do print nums print $ computeReciprocals1 nums print $ computeReciprocals2 nums -- Haskellでは0除算は例外ではなく∞(Infinity)になる computeReciprocals1 :: [Double] -> [Double] computeReciprocals1 = map (1/) nums :: [Double] nums = [0, 1, 2, 3, 4, 5, 0, 7, 8, 9, 10, 0] -- Either a b型を利用して0除算を判別 computeReciprocals2 :: [Double] -> [Either String Double] computeReciprocals2 = map (\x -> if x == 0 then Left "Zero Division" else Right (1/x))
入出力結果(Terminal, runghc)
$ runghc Sample.hs [0.0,1.0,2.0,3.0,4.0,5.0,0.0,7.0,8.0,9.0,10.0,0.0] [Infinity,1.0,0.5,0.3333333333333333,0.25,0.2,Infinity,0.14285714285714285,0.125,0.1111111111111111,0.1,Infinity] [Left "Zero Division",Right 1.0,Right 0.5,Right 0.3333333333333333,Right 0.25,Right 0.2,Left "Zero Division",Right 0.14285714285714285,Right 0.125,Right 0.1111111111111111,Right 0.1,Left "Zero Division"] $
慣れるまでは{-# OPTIONS -Wall -Werror #-}の記述を消さずに細かく型を指定していくことに。
0 コメント:
コメントを投稿