Home Articles

这些模式对我来说看起来很详尽,“非详尽模式错误”?为什么?

Asked
Viewed 113 times
0

问题

在从Haskell书中记笔记时,此代码示例应该返回: Left [NameEmpty, AgeTooLow] ,但它只返回第一个案例 Left [NameEmpty] . 然后,当我将函数 mkPerson2 结果传递给它应返回 Right Person _ _ 时,我得到一个“非详尽模式```错误 . 我已经查看了这段代码很长一段时间了,但它对我来说是正确的 . 我在这里错过了什么?关于这个问题的任何解释都将非常感谢,谢谢!

Book I'm using

代码

module EqCaseGuard where

type Name = String
type Age  = Integer
type ValidatePerson a = Either [PersonInvalid] a

data Person = Person Name Age deriving Show

data PersonInvalid = NameEmpty
                   | AgeTooLow
                   deriving Eq

ageOkay :: Age -> Either [PersonInvalid] Age
ageOkay age = case age >= 0 of
True  -> Right age
False -> Left [AgeTooLow]

nameOkay :: Name -> Either [PersonInvalid] Name
nameOkay name = case name /= "" of
True  -> Right name
False -> Left [NameEmpty]

mkPerson2 :: Name -> Age -> ValidatePerson Person
mkPerson2 name age = mkPerson2' (nameOkay name) (ageOkay age)

mkPerson2' :: ValidatePerson Name -> ValidatePerson Age -> ValidatePerson Person
mKPerson2' (Right nameOk) (Right ageOk) = Right (Person nameOk ageOk)
mKPerson2' (Left badName) (Left badAge) = Left (badName ++ badAge)
mkPerson2' (Left badName)  _            = Left badName
mkPerson2' _              (Left badAge) = Left badAge

错误

*EqCaseGuard> mkPerson2 "jack" 22
*** Exception: eqCaseGuard.hs:(54,1)-(55,53): Non-exhaustive patterns in function mkPerson2'

*EqCaseGuard> mkPerson2 "" (-1)
Left [NameEmpty]
*EqCaseGuard>

1 Answer

  • 9

    您在前两个定义中使用了大写字母K:

    mKPerson2' (Right nameOk) (Right ageOk) = Right (Person nameOk ageOk)
     ^
    
    mKPerson2' (Left badName) (Left badAge) = Left (badName ++ badAge)
     ^
    

Related