我如何在这里正确编写模式匹配?
How do I write the pattern matching correctly here?
以下代码有效:
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 案例不同?
不一样,是因为有错误:
myFindMax (Atom x) = getAtom x
将尝试调用 getAtom
到一个(通常)不是 Atom
值的值。该模式已经完成了 getAtom
函数的工作。你应该写:
myFindMax (Atom x) = x
以下代码有效:
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 案例不同?
不一样,是因为有错误:
myFindMax (Atom x) = getAtom x
将尝试调用 getAtom
到一个(通常)不是 Atom
值的值。该模式已经完成了 getAtom
函数的工作。你应该写:
myFindMax (Atom x) = x