計算機科学のブログ

型によるプログラミング 直積型と直和型 図形、円、正方形、長方形、外周と面積

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT3(型によるプログラミング)、LESSON 16(直積型と直和型)、16.5(練習問題)Q16-2の解答を求めてみる。

コード

lesson/app/Main.hs

module Main where

import Lib
  ( perimeterAndArea,
    shapes,
  )

main :: IO ()
main = do
  print shapes
  mapM_ print perimeterAndArea

lesson/src/Lib.hs

module Lib
  ( shapes,
    perimeterAndArea,
  )
where

shapes :: [Shape]
shapes =
  [ ShapeCircle $ Circle 5,
    ShapeSquare $ Square 10,
    ShapeRectangle $ Rectangle 2 3
  ]

perimeters :: [Unit]
perimeters = map perimeter shapes

areas :: [Unit]
areas = map area shapes

perimeterAndArea :: [(Unit, Unit)]
perimeterAndArea = zip perimeters areas

data Shape
  = ShapeCircle Circle
  | ShapeSquare Square
  | ShapeRectangle Rectangle
  deriving (Show)

type Unit = Double

perimeter :: Shape -> Unit
perimeter (ShapeCircle (Circle r)) = 2 * r * pi
perimeter (ShapeSquare (Square w)) = 4 * 2
perimeter (ShapeRectangle (Rectangle w h)) = 2 * (w + h)

area :: Shape -> Unit
area (ShapeCircle (Circle r)) = r * r * pi
area (ShapeSquare (Square w)) = w * w
area (ShapeRectangle (Rectangle w h)) = w * h

type Radius = Double

data Circle = Circle Radius deriving (Show)

type Width = Double

type Height = Double

data Square = Square Width deriving (Show)

data Rectangle = Rectangle
  { width :: Width,
    height :: Height
  }
  deriving (Show)

入出力結果(Terminal, Zsh)

% stack exec lesson-exe
[ShapeCircle (Circle 5.0),ShapeSquare (Square 10.0),ShapeRectangle (Rectangle {width = 2.0, height = 3.0})]
(31.41592653589793,78.53981633974483)
(8.0,100.0)
(10.0,6.0)
%