我的树是由以下定义的
data Tree a = Leaf a | Node (Tree a) (Tree a)
deriving (Show)
我也声明一个测试树。
myTree = Node (Node (Leaf 1) (Leaf 2)) (Leaf 3)
我想要做的是创建一个函数 maptree f,它将作用于 Leaf。更具体地说,f x = x +1
,
那么 maptree f myTree
将返回
Node (Node (Leaf 2) (Leaf 3)) (Leaf 4)
我的方案是
maptree f (Leaf a)= Leaf (f a)
maptree f (Node xl xr ) = Node (maptree xl) (maptree xr)
但它会返回以下错误。
Couldn't match expected type `Tree a'
against inferred type `Tree t -> Tree t'
Probable cause: `maptree' is applied to too few arguments
In the first argument of `Node', namely `(maptree xl)'
In the expression: Node (maptree xl) (maptree xr)
失败,模块已加载:无。
但是,如果我这样做
maptree (Leaf a)= Leaf ( a + 1)
maptree (Node xl xr ) = Node (maptree xl) (maptree xr)
它确实有效。
我看不出第一个函数和第二个函数之间的区别。我如何得到错误?谢谢。