所以我试图设计一个函数来返回一个二进制树,它是最初发送的二叉树的镜像。我想我已经差不多完成但是我得到一个奇怪的“无法匹配预期的类型。这是我的代码:
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)
答案 0 :(得分: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
的正确定义的模式匹配,问题得以解决。