2013年11月5日火曜日

開発環境

初めてのコンピュータサイエンス(Jennifer CampbellPaul GriesJason MontojoGreg Wilson(著)長尾 高弘(翻訳))の6章(条件分岐)、6.5(練習問題)、5をHaskellで解いてみる。

その他参考書籍

6.5(練習問題)、5.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}

main :: IO ()
main = mapM_ putStrLn $
             map (\(a, b) -> "light = " ++ show a ++ ", temperature = " ++
                             show b ++ " 自動カメラのスイッチ " ++
                             xor1 a b ++ ' ':xor2 a b)
                 lightAndTemperatures

xor1 :: Double -> Double -> String
xor1 a b | (a < 0.01 || b > 0.0) && not (a < 0.01 && b > 0.0) = "on"
         | otherwise = "off"

xor2 :: Double -> Double -> String
xor2 a b | (a < 0.01) /= (b > 0.0) = "on"
         | otherwise = "off"

lightAndTemperatures :: [(Double, Double)]
lightAndTemperatures = [(0.001, -1.0), (0.001, 1.0), (0.01, -1.0), (0.01, 1.0)]

入出力結果(Terminal, runghc)

$ runghc Sample.hs
light = 1.0e-3, temperature = -1.0 自動カメラのスイッチ on on
light = 1.0e-3, temperature = 1.0 自動カメラのスイッチ off off
light = 1.0e-2, temperature = -1.0 自動カメラのスイッチ off off
light = 1.0e-2, temperature = 1.0 自動カメラのスイッチ on on
$

{-# OPTIONS -Wall -Werror #-}を記述してるから、細かく型を指定(:: Double)しないと警告がいっぱい出た。慣れるまでは{-# OPTIONS -Wall -Werror #-}の記述を消さずに細かく型を指定していくことに。

0 コメント:

コメントを投稿