导致"Couldn't match expected type with actual type"的原因



以下代码有效:

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 getBloodType(johnDoe) getBloodType(janeESmith))替换print(canDonateTo johnDoeBloodType janeESmithBloodType),它会给出错误:

无法将预期类型"血型"与实际类型"患者"匹配

这里函数的类型签名是:

canDonateTo :: BloodType -> BloodType -> Bool
getBloodType :: Patient -> BloodType

因此,getBloodType(johnDoe)被认为是Patient而不是BloodType。但是当我把这个函数的输出保存在johnDoeBloodType中时,它被认为是BloodType

是什么造成了这种困境?

在Haskell中,f x将参数x应用于函数f

当你写:

print(canDonateTo getBloodType(johnDoe) getBloodType(janeESmith))

它相当于:

print (canDonateTo getBloodType johnDoe getBloodType janeESmith)

也许你的意思是:

print (canDonateTo (getBloodType johnDoe) (getBloodType janeESmith))

相关内容

最新更新