型の紹介 カスタム型の作成 パターンマッチ
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT2(型の紹介)、LESSON 12(カスタム型の作成)、12.5(練習問題)Q12-1の解答を求めてみる。
コード
lesson/app/Main.hs
module Main where
import Lib
main :: IO ()
main = do
print patients
print $ map bloodType patients
mapM_ print $ patientCanDonateTo <$> patients <*> patients
lesson/src/Lib.hs
module Lib
( patients,
patientCanDonateTo,
bloodType,
)
where
data Patient = Patient
{ bloodType :: BloodType
}
deriving (Show)
data ABOType = A | B | AB | O
deriving (Show)
data RhType = Pos | Neg
deriving (Show)
data BloodType = BloodType ABOType RhType
deriving (Show)
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
patientCanDonateTo :: Patient -> Patient -> Bool
patientCanDonateTo p1 p2 = canDonateTo (bloodType p1) (bloodType p2)
patients :: [Patient]
patients =
[ Patient {bloodType = BloodType A Pos},
Patient {bloodType = BloodType B Pos},
Patient {bloodType = BloodType AB Pos},
Patient {bloodType = BloodType O Pos}
]
入出力結果(Terminal, Zsh)
% stack build
lesson-0.1.0.0: unregistering (local file changes: src/Lib.hs)
lesson> build (lib + exe)
Preprocessing library for lesson-0.1.0.0..
Building library for lesson-0.1.0.0..
[2 of 2] Compiling Lib
Preprocessing executable 'lesson-exe' for lesson-0.1.0.0..
Building executable 'lesson-exe' for lesson-0.1.0.0..
lesson> copy/register
Installing library in /Users/…/lesson/.stack-work/install/x86_64-osx/58a4c4d937f77ed7ad33a3d831dc078cdd38bc2500aef58d99dd5ff42214f933/9.0.2/lib/x86_64-osx-ghc-9.0.2/lesson-0.1.0.0-CIOIkpTgcfQI9akDJnwnSd
Installing executable lesson-exe in /Users/…/lesson/.stack-work/install/x86_64-osx/58a4c4d937f77ed7ad33a3d831dc078cdd38bc2500aef58d99dd5ff42214f933/9.0.2/bin
Registering library for lesson-0.1.0.0..
% stack exec lesson-exe
[Patient {bloodType = BloodType A Pos},Patient {bloodType = BloodType B Pos},Patient {bloodType = BloodType AB Pos},Patient {bloodType = BloodType O Pos}]
[BloodType A Pos,BloodType B Pos,BloodType AB Pos,BloodType O Pos]
True
False
True
False
False
True
True
False
False
False
True
False
True
True
True
True
%