型の紹介 - カスタム型の作成 - パターンマッチング
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT2(型の紹介)、LESSON 12(カスタム型の作成)、12.4(練習問題)、Q12-1の解答を求めてみる。
コード
sample.hs
import Distribution.PackageDescription (cAnd)
main :: IO ()
main = do
print $ canDonateToPatient johnDoe jackieSmith
print $ canDonateToPatient jackieSmith johnDoe
type FirstName = String
type LastName = String
type MiddleName = String
data Name = Name FirstName LastName |
NameWithMiddleName FirstName MiddleName LastName
data Sex = Male | Female
data RhType = Pos | Neg
data ABOType = A | B | AB | O
data BloodType = BloodType ABOType RhType
data Patient = Patient {
name :: Name,
sex :: Sex,
age :: Int,
height :: Int,
weight :: Int,
bloodType :: BloodType
}
canDonateTo :: BloodType -> BloodType -> Bool
canDonateTo (BloodType O _) _ = True
canDonateTo _ (BloodType AB _) = True
canDonateTo (BloodType A _) (BloodType A _) = True
canDonateTo (BloodType B _) (BloodType B _) = True
canDonateTo _ _ = False
canDonateToPatient :: Patient -> Patient -> Bool
canDonateToPatient p1 p2 = canDonateTo (bloodType p1) (bloodType p2)
johnDoe :: Patient
johnDoe = Patient {
name = Name "John" "Doe",
sex = Male,
age = 30,
height = 74,
weight = 200,
bloodType = BloodType AB Pos
}
jackieSmith :: Patient
jackieSmith = Patient {
name = Name "Jackie" "Smith",
age = 43,
sex = Female,
height = 62,
weight = 115,
bloodType = BloodType O Neg
}
入出力結果(Terminal, Zsh)
% runghc sample.hs
False
True
%