以下代码有效:
data MyList a = Atom a | Cons a (MyList a) deriving (Show)
getAtom (Atom a) = a
myFindMax :: (Ord a) => MyList a -> a
myFindMax (Cons x xs) = let restMax = myFindMax xs in
if x > restMax then x else restMax
myFindMax x = getAtom x
但是当我写作
myFindMax (Atom x) = getAtom x
在其他模式之前,我收到错误
Couldn't match expected type ‘MyList a’ with actual type ‘a’
‘a’ is a rigid type variable bound by
the type signature for myFindMax :: Ord a => MyList a -> a
at myList.hs:5:14
为什么Atom案例与Cons案例不同?
答案 0 :(得分:7)
没有什么不同,这是因为有错误:
myFindMax (Atom x) = getAtom x
将尝试将getAtom
调用为非(通常)Atom
值的值。该模式已经完成getAtom
函数的工作。你应该写:
myFindMax (Atom x) = x