型によるプログラミング 直積型と直和型 ブックストアプログラムを作成する
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT3(型によるプログラミング)、LESSON 16(直積型と直和型)、16.2(ブックストアプログラムを作成する)、クイックチェック 16-3の解答を求めてみる。
コード
lesson/app/Main.hs
module Main where
import Lib
main :: IO ()
main = do
mapM_ print creators
lesson/src/Lib.hs
module Lib
( creators,
)
where
storeItems :: [StoreItem]
storeItems =
[ BookItem $ Book $ AuthorCreator $ Author $ Name "firstName" "lastName",
RecordItem $
VinylRecord $
ArtistCreator $
Person $
NameWithMiddle "firstName" "middleName" "lastName",
ToyItem $ CollectibleToy "toy"
]
creators :: [String]
creators = map madeBy storeItems
type FirstName = String
type LastName = String
type MiddleName = String
data Name
= Name FirstName LastName
| NameWithMiddle FirstName MiddleName LastName
| TwoInitialsWithLast Char Char LastName
deriving (Show)
data Author = Author Name deriving (Show)
data Artist = Person Name | Band String deriving (Show)
data Creator
= AuthorCreator Author
| ArtistCreator Artist
deriving (Show)
data Book = Book
{ author :: Creator
}
data VinylRecord = VinylRecord
{ artist :: Creator
}
data CollectibleToy = CollectibleToy
{ name :: String
}
data StoreItem
= BookItem Book
| RecordItem VinylRecord
| ToyItem CollectibleToy
madeBy :: StoreItem -> String
madeBy (BookItem book) = show $ author book
madeBy (RecordItem vinylRecord) = show $ artist vinylRecord
madeBy _ = "unknown"
入出力結果(Terminal, Zsh)
% stack exec lesson-exe
"AuthorCreator (Author (Name \"firstName\" \"lastName\"))"
"ArtistCreator (Person (NameWithMiddle \"firstName\" \"middleName\" \"lastName\"))"
"unknown"
%