型によるプログラミング 直積型と直和型 OR、追加
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT3(型によるプログラミング)、LESSON16(直積型と直和型)、16.54(練習問題)Q16-1の解答を求めてみる。
コード
data Book = Book {bookPrice :: Double} deriving (Show)
data VinylRecord = VinylRecord {recordPrice :: Double}
deriving (Show)
data CollectibleToy = CollectibleToy {toyPrice :: Double}
deriving (Show)
data Pamphlet = Pamphlet
{ title :: String,
description :: String,
contact :: String
}
deriving (Show)
data StoreItem
= BookItem Book
| RecordItem VinylRecord
| ToyItem CollectibleToy
| PamphletItem Pamphlet
deriving (Show)
price :: StoreItem -> Double
price (BookItem book) = bookPrice book
price (RecordItem record) = recordPrice record
price (ToyItem toy) = toyPrice toy
price (PamphletItem _) = 0
pamphlet =
PamphletItem
Pamphlet
{ title = "Title",
description = "Description",
contact = "Contact"
}
main = do
print pamphlet
print $ price pamphlet
入出力結果(Terminal, Zsh)
% runghc sample1.hs
PamphletItem (Pamphlet {title = "Title", description = "Description", contact = "Contact"})
0.0
%