如何正确编写模式匹配?

时间:2015-08-06 06:23:53

标签: 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

但是当我写作

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案例不同?

1 个答案:

答案 0 :(得分:7)

没有什么不同,这是因为有错误:

myFindMax (Atom x) = getAtom x

将尝试将getAtom调用为非(通常)Atom值的值。该模式已经完成getAtom函数的工作。你应该写:

myFindMax (Atom x) = x