haskell 导致“预期类型与实际类型不匹配”的原因

k4emjkb1  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(163)

下面的代码是有效的:

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),则会出现错误:
无法将预期类型“BloodType”与实际类型“Patient”匹配
下面是函数的类型签名:

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

因此,getBloodType(johnDoe)被认为是Patient,而不是BloodType。但是当我将此函数的输出保存在johnDoeBloodType中时,它被认为是BloodType
是什么造成了这种困境?

qjp7pelc

qjp7pelc1#

在Haskell中,f x将自变量x应用于函数f
当你写:

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

...它相当于:

print (canDonateTo getBloodType johnDoe getBloodType janeESmith)

您的意思可能是:

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

相关问题