計算機科学のブログ

Haskell - 型によるプログラミング - 直積型と直和型 - レコード構文の処理の制限

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

コード

sample.hs

main :: IO ()
main = do
  mapM_
    (print . price)
    [ BookItem Book {author = Creator, bookPrice = 10},
      RecordItem VinylRecond {artist = Creator, recordPrice=20},
      ToyItem CollectibleToy {name = "name", toyPrice=30},
      PamphletItem Pamphlet {title = "title", description="description", address= "address"}
    ]

data Creator = Creator deriving (Show)

data Book = Book {
    author :: Creator,
    bookPrice :: Double
  }

data VinylRecond = VinylRecond { 
    artist :: Creator,
    recordPrice :: Double
    }

data CollectibleToy = CollectibleToy {
     name :: String,
     toyPrice :: Double
     }

data Pamphlet = Pamphlet {
    title :: String,
    description :: String,
    address :: String
}
data StoreItem
  = BookItem Book
  | RecordItem VinylRecond
  | ToyItem CollectibleToy
  | PamphletItem Pamphlet

price :: StoreItem -> Double
price (BookItem book) = bookPrice book
price (RecordItem record) = recordPrice record
price (ToyItem toy) = toyPrice toy
price (PamphletItem pamphlet) = 0

madeBy :: StoreItem -> String
madeBy (BookItem book) = show $ author book
madeBy (RecordItem record) = show $ artist record
madeBy (ToyItem toy) = name toy
madeBy (PamphletItem pamphlet) = address pamphlet

入出力結果(Terminal, Zsh)

% runghc sample.hs
10.0
20.0
30.0
0.0
%