計算機科学のブログ

Haskell - コードの整理とプロジェクトのビルド - stackを使ってプロジェクトをビルトする - ライブラリモジュール

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT6(コードの整理とプロジェクトのビルド)、LESSON 35(stackを使ってプロジェクトをビルトする)、35.6(練習問題)、Q35-2の解答を求めてみる。

コード

pizza/app/Main.hs

module Main (main) where

-- import Lib
import Pizza(comparePizzas, describePizza)

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

コード

pizza/src/Pizza.hs

module Pizza(comparePizzas, describePizza) where

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

type Pizza = (Double,Double)

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

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

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

入出力結果(Terminal, Zsh)

 % stack build
pizza-0.1.0.0: unregistering (local file changes: app/Main.hs)
pizza> build (lib + exe) with ghc-9.8.4
Preprocessing library for pizza-0.1.0.0..
Building library for pizza-0.1.0.0..
Preprocessing executable 'pizza-exe' for pizza-0.1.0.0..
Building executable 'pizza-exe' for pizza-0.1.0.0..
[1 of 2] Compiling Main [Source file changed]
[3 of 3] Linking .stack-work/dist/aarch64-osx/ghc-9.8.4/build/pizza-exe/pizza-exe [Objects changed]
ld: warning: -U option is redundant when using -undefined dynamic_lookup
pizza> copy/register
Installing library in /Users/.../pizza/.stack-work/install/aarch64-osx/e7436b3217cf53d6b9beeebd2bdc5dd8dcab6f8595b8bde259631442ce745f25/9.8.4/lib/aarch64-osx-ghc-9.8.4/pizza-0.1.0.0-8ICGlCpv46h8Ky1ot0WBN9
Installing executable pizza-exe in /Users/.../pizza/.stack-work/install/aarch64-osx/e7436b3217cf53d6b9beeebd2bdc5dd8dcab6f8595b8bde259631442ce745f25/9.8.4/bin
Registering library for pizza-0.1.0.0..
% stack exec pizza-exe
What is the size of pizza 1
5
What is the cost of pizza 1
10
What is the size of pizza 2
6
What is the cost of pizza 2
20
The 5.0 pizza is cheaper at 0.5092958178940651 per square inch
% stack exec pizza-exe
What is the size of pizza 1
6
What is the cost of pizza 1
20
What is the size of pizza 2
5
What is the cost of pizza 2
10
The 5.0 pizza is cheaper at 0.5092958178940651 per square inch
%