計算機科学のブログ

コンテキストでの型の操作 do表記を使ってMonadを扱いやすくする do表記を>>=演算子、>>演算子、return、ラムダ関数で書き換える

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT5(コンテキストでの型の操作)、LESSON 31(do表記を使ってMonadを扱いやすくする)、31.4(練習問題)Q31-1の解答を求めてみる。

コード

type Pizza = (Double, Double)

areaGiveDiameter :: Double -> Double
areaGiveDiameter size = pi * (size / 2)^2

costPerInch :: Pizza -> Double
costPerInch (size, cost) = cost / areaGiveDiameter size

comparePizzas :: Pizza -> Pizza -> Pizza
comparePizzas p1 p2 =
    let costP1 = costPerInch p1
        costP2 = costPerInch p2
    in if costP1 < costP2
       then p1
       else p2

describePizza :: Pizza -> String
describePizza (size, cost) =
    let costSqInch = costPerInch (size, cost)
    in mconcat ["The ", show size, " pizza ", "is cheaper at ",
                show costSqInch, " per square inch"]

main :: IO ()
main = return "What is the size of pizza 1" >>= 
    putStrLn >>
    getLine >>=
        (\size1 ->
            return "What is the cost of pizza 1" >>=
            putStrLn >>
            getLine >>=
                (\cost1 ->
                    return "What is the size of pizza 2" >>=
                    putStrLn >>
                    getLine >>=
                        (\size2 ->
                            return "What is the cost of pizza 2" >>=
                            putStrLn >>
                            getLine >>=
                                (\cost2 ->
                                    (\pizza1 ->
                                        (\pizza2 ->
                                            (\betterPizza ->
                                                return (describePizza betterPizza) >>=
                                                putStrLn)
                                            (comparePizzas pizza1 pizza2))
                                        (read size2, read cost2))
                                    (read size1, read cost1)))))

入出力結果(Terminal, Zsh)

% runghc sample1.hs
What is the size of pizza 1
12
What is the cost of pizza 1
15
What is the size of pizza 2
18
What is the cost of pizza 2
20
The 18.0 pizza is cheaper at 7.859503362562734e-2 per square inch
%