man*_*479 0 haskell pattern-matching
以下代码有效:
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
Run Code Online (Sandbox Code Playgroud)
但是当我写作
myFindMax (Atom x) = getAtom x
Run Code Online (Sandbox Code Playgroud)
在其他模式之前,我得到了错误
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
Run Code Online (Sandbox Code Playgroud)
为什么Atom案例与Cons案例不同?
它没有什么不同,这是因为有一个错误:
myFindMax (Atom x) = getAtom x
Run Code Online (Sandbox Code Playgroud)
将尝试调用getAtom
不是(通常)Atom
值的值.该模式已经完成了该getAtom
功能的工作.你应该写:
myFindMax (Atom x) = x
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
51 次 |
最近记录: |