以下代碼有效:
type FirstName = String
type MiddleName = String
type LastName = String
data Name = Name FirstName LastName | NameWithMiddle FirstName MiddleName LastName
data Sex = Male | Female
showName :: Name -> String
showName (Name f l) = f " " l
showName (NameWithMiddle f m l) = f " " m " " l
data RhType = Pos | Neg
data ABOType = A | B | AB | O
data BloodType = BloodType ABOType RhType
showRh :: RhType -> String
showRh Pos = " "
showRh Neg = "-"
showABO :: ABOType -> String
showABO A = "A"
showABO B = "B"
showABO AB = "AB"
showABO O = "O"
showBloodType :: BloodType -> String
showBloodType (BloodType abo rh) = showABO abo showRh rh
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 --otherwise
data Patient = Patient Name Sex Int Int Int BloodType
johnDoe :: Patient
johnDoe = Patient (Name "John" "Doe") Male 30 74 200 (BloodType AB Pos)
janeESmith :: Patient
janeESmith = Patient (NameWithMiddle "Jane" "Elizabeth" "Smith") Female 28 62 140 (BloodType AB Pos)
getName :: Patient -> Name
getName (Patient n _ _ _ _ _) = n
getAge :: Patient -> Int
getAge (Patient _ _ a _ _ _) = a
getBloodType :: Patient -> BloodType
getBloodType (Patient _ _ _ _ _ bt) = bt
main = do
let johnDoeBloodType = getBloodType(johnDoe)
let janeESmithBloodType = getBloodType(janeESmith)
print(canDonateTo (BloodType AB Pos) (BloodType AB Pos))
print(canDonateTo johnDoeBloodType janeESmithBloodType)
但是,如果我替換print(canDonateTo johnDoeBloodType janeESmithBloodType)為print(canDonateTo getBloodType(johnDoe) getBloodType(janeESmith)),則會出現錯誤:
無法將預期型別“血型”與實際型別“患者”匹配
這里函式的型別簽名是:
canDonateTo :: BloodType -> BloodType -> Bool
getBloodType :: Patient -> BloodType
因此,getBloodType(johnDoe)被認為是 aPatient而不是BloodType. 但是當我將此函式的輸出保存在 中時johnDoeBloodType,它被認為是BloodType.
是什么造成了這里的困境?
uj5u.com熱心網友回復:
在 Haskell 中,f x將引數應用于x函式f。
當你寫:
print(canDonateTo getBloodType(johnDoe) getBloodType(janeESmith))
...它相當于:
print (canDonateTo getBloodType johnDoe getBloodType janeESmith)
也許你的意思是:
print (canDonateTo (getBloodType johnDoe) (getBloodType janeESmith))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528493.html
標籤:哈斯克尔
