1

所以我试图设计一个函数来返回一个二叉树,它是最初发送的二叉树的镜像。我想我几乎完成了,但我得到一个奇怪的“无法匹配预期的类型。这是我的代码:

mirror :: BinTree a -> BinTree a    
mirror (Node x tL tR) = Node x (mirror tR) (mirror tL)

这是错误:

hw1.hs:84:30:
    Couldn't match expected type `a' with actual type `BinTree a'
      `a' is a rigid type variable bound by
          the type signature for mirror :: BinTree a -> BinTree a
          at hw1.hs:83:11
    In the first argument of `Node', namely `x'
    In the expression: Node x (mirror tR) (mirror tL)
    In an equation for `mirror':
        mirror (Node tL x tR) = Node x (mirror tR) (mirror tL)

hw1.hs:84:33:
    Couldn't match expected type `a' with actual type `BinTree a'
      `a' is a rigid type variable bound by
          the type signature for mirror :: BinTree a -> BinTree a
          at hw1.hs:83:11
    In the return type of a call of `mirror'
    In the second argument of `Node', namely `(mirror tR)'
    In the expression: Node x (mirror tR) (mirror tL)
Failed, modules loaded: none.

是我的错。我对树的定义不同。

data BinTree a = Empty | Node (BinTree a) a (BinTree a) deriving (Eq,Show)

*新功能应该是:*

mirror :: BinTree a -> BinTree a
mirror Empty = Empty
mirror (Node tL x tR) = Node (mirror tR) x (mirror tL)
4

1 回答 1

1

在@Davorak 的建议下,我将我的评论变成了答案,即使它并没有真正回答问题,只是说明了问题。


使用定义时

data BinTree a = Empty | Node a (BinTree a) (BinTree a) deriving (Eq)

OP的原始代码编译,但没有编译,因为他使用的定义是

data BinTree a = Empty | Node (BinTree a) a (BinTree a) deriving (Eq)

通过修改函数mirror以在 的正确定义上进行模式匹配BinTree a,问题得到解决。

于 2013-09-03T00:09:47.023 回答