Haskell - 型によるプログラミング - 直積型と直和型 - 3つの図形、円、正方形、長方形、外周、面積
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT3(型によるプログラミング)、LESSON 16(直積型と直和型)、16.5(練習問題)、Q16-1の解答を求めてみる。
コード
sample.hs
main :: IO ()
main = do
mapM_
(\shape -> print $ show shape ++ ", " ++ show (perimeter shape) ++ ", " ++ show (area shape))
shapes
type Radius = Double
type Side = Double
data Shape = Circle Radius | Square Side | Rectangle Side Side deriving (Show)
perimeter :: Shape -> Double
perimeter (Circle r) = 2 * pi * r
perimeter (Square s) = 4 * s
perimeter (Rectangle w h) = 2 * (w + h)
area :: Shape -> Double
area (Circle r) = r ^ 2 * pi
area (Square s) = s ^ 2
area (Rectangle w h) = w * h
circle :: Shape
circle = Circle 2.5
square :: Shape
square = Square 11.5
rectangle :: Shape
rectangle = Rectangle 11.1 25
shapes :: [Shape]
shapes = [circle, square, rectangle]
入出力結果(Terminal, Zsh)
% runghc sample.hs
"Circle 2.5, 15.707963267948966, 19.634954084936208"
"Square 11.5, 46.0, 132.25"
"Rectangle 11.1 25.0, 72.2, 277.5"
%