2013年10月30日水曜日

開発環境

初めてのコンピュータサイエンス(Jennifer CampbellPaul GriesJason MontojoGreg Wilson(著)長尾 高弘(翻訳))の3章(文字列)の3.1(文字列)、3.2(エスケープ文字)、3.3(マルチライン文字列)、3.4(print(関数))、3.5(整形された文字列)、3.6(ユーザー入力)、3.7(まとめ)、3.8(練習問題)、1、2、3、4、5、6、7をHaskellで解いてみる。

その他参考書籍

3.8(練習問題)、1、2、3、4、5、6、7.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}

main :: IO ()
main = do
    putStrLn "1."
    mapM_ putStrLn $ map (\(x, y) -> x ++ '\n':y)
                         [("Computer" ++ " Science", "Computer Science"),
                          (concat $ replicate 3 "H2O", "H2OH2OH2O"),
                          (concat $ replicate 0 "CO2", "")]
    putStrLn "2."
    mapM_ putStrLn ["They'll hibernate during the winter.",
                    "\"Absolutely not, \" he said.",
                    "\"He said, 'Absolutely not,'\" recalled Mel.",
                    "hydrogen sulfide",
                    "left\\right"]
    putStrLn "3."
    putStrLn "A\nB\nC"
    putStrLn "4."
    putStrLn $ show . length $ ""
    putStrLn "5."
    let x = 3 :: Int
        y = 12.5 :: Double
    mapM_ putStrLn ["The rabbit is " ++ show x ++ ".",
                    "The rabbit is " ++ show x ++ " years old.",
                    show y ++ " is average.",
                    show y ++ " * " ++ show x,
                    show y ++ " * " ++ show x ++ " is " ++
                    (show $ fromIntegral x * y)]
    putStrLn "6."
    mapM_ putStrLn [(concat $ replicate 3 "0") ++ show (8 :: Int),
                    show (8 :: Int) ++ " #"]
    putStrLn "7."
    putStrLn "数値を入力"
    line <- getLine
    putStrLn $ show (read line :: Double)

入出力結果(Terminal, runghc)

$ runghc Sample.hs
1.
Computer Science
Computer Science
H2OH2OH2O
H2OH2OH2O


2.
They'll hibernate during the winter.
"Absolutely not, " he said.
"He said, 'Absolutely not,'" recalled Mel.
hydrogen sulfide
left\right
3.
A
B
C
4.
0
5.
The rabbit is 3.
The rabbit is 3 years old.
12.5 is average.
12.5 * 3
12.5 * 3 is 37.5
6.
0008
8 #
7.
数値を入力
8
8.0
$

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

0 コメント:

コメントを投稿