型によるプログラミング 直積型と直和型 モデル化、レコード構文
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT3(型によるプログラミング)、LESSON 16(直積型と直和型)、16.5(練習問題)Q16-1の解答を求めてみる。
コード
-- Q16-1
type FirstName = String
type LastName = String
type MiddleName = String
data Name = Name FirstName LastName
| NameWithMiddle FirstName MiddleName LastName
data Author = Author Name
data Creator = AuthorCreator Author
data Book = Book
{ author :: Creator,
isbn :: String,
bookTitle :: String,
bookYear :: Int,
bookPrice :: Double
}
data Pamphlet = Pamphlet {
pamphletTitle :: String
}
data StoreItem = BookItem Book | StoreItem Pamphlet
price :: StoreItem -> Double
price (BookItem book) = bookPrice book
price (StoreItem pamphlet) = 0.0
pamphlet :: Pamphlet
pamphlet = Pamphlet {pamphletTitle = "Title"}
book :: Book
book = Book {
author = AuthorCreator (Author (Name "fname" "lname")),
isbn = "1234567890123",
bookTitle = "book title",
bookYear = 2022,
bookPrice = 2000
}
入出力結果(Terminal, Zsh)
% ghci
GHCi, version 8.10.5: https://www.haskell.org/ghc/ :? for help
macro 'doc' overwrites builtin command. Use ':def!' to overwrite.
(0.00 secs, 0 bytes)
(0.00 secs, 0 bytes)
Loaded GHCi configuration from /.../.ghc/ghci.conf
Prelude
λ> :load sample1
[1 of 1] Compiling Main ( sample1.hs, interpreted )
Ok, one module loaded.
(0.01 secs,)
*Main
λ> price (BookItem book)
2000.0
it :: Double
(0.00 secs, 67,776 bytes)
*Main
λ> price (StoreItem pamphlet)
0.0
it :: Double
(0.00 secs, 61,672 bytes)
*Main
λ> :quit
Leaving GHCi.
%