2013年10月28日月曜日

開発環境

初めてのコンピュータサイエンス(Jennifer CampbellPaul GriesJason MontojoGreg Wilson(著)長尾 高弘(翻訳))の2章(Python入門)の2.10(練習問題)、9をHaskellで解いてみる。

その他参考書籍

9.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}

main :: IO ()
main = mapM_  putStrLn $
              map (\(x, y) -> "距離 " ++ show (x :: Int) ++ "km  燃費 " ++ 
                              show (y :: Int) ++ " mpg 必要なガソリンの量 " ++
                              (show $ litresNeeded (fromIntegral x)
                                                   (fromIntegral y)) ++
                              "リットル")
                  [(150, 30), (100, 30)]

litresNeeded :: Double -> Double -> Double
litresNeeded a = (*a) . (/100) . convertMileage

convertMileage :: Double -> Double
convertMileage = (100/) . convertMpgToKmpl

convertMpgToKmpl :: Double -> Double
convertMpgToKmpl = (/gallonToLitre 1) . mileToKm

gallonToLitre :: Double -> Double
gallonToLitre = (3.78541178*)

mileToKm :: Double -> Double
mileToKm = (1.609344*)

入出力結果(Terminal, runghc)

$ runghc Sample.hs
距離 150km  燃費 30 mpg 必要なガソリンの量 11.760729154239241リットル
距離 100km  燃費 30 mpg 必要なガソリンの量 7.84048610282616リットル
$

0 コメント:

コメントを投稿