错误类型
问题描述:
我做练习用二叉树:错误类型
data BinaryTree a =
Leaf
| Node (BinaryTree a) a (BinaryTree a)
deriving (Show)
我实现了树折叠功能:
foldTree :: (a -> b -> b -> b) -> b -> BinaryTree a -> b
foldTree _ start Leaf = start
foldTree f start (Node left x right) = f x (foldTree f start left) (foldTree f start right)
现在我试图重写我的老地图功能使用折叠:
mapTree' :: (a -> b) -> BinaryTree a -> BinaryTree b
mapTree' f bt = foldTree (\l x r -> Node l (f x) r) Leaf bt
但是,它告诉我,x
在上述lambda类型为二叉树的
x :: BinaryTree b (bound at app/Main.hs:85:30)
我很困惑,因为如果我在ghci
做:t Node
我得到:
Node :: BinaryTree a -> a -> BinaryTree a -> BinaryTree a
所以,在我的脑海x
应该a
型的,因为它是在的中间位置Node
构造函数。
我哪里错了?
答
更改要么foldTree
拥有的BinaryTree
foldTree :: (b -> a -> b -> b) -> b -> BinaryTree a -> b
-------------^----^
foldTree _ start Leaf = start
foldTree f start (Node left x right) = f (foldTree f start left) x (foldTree f start right)
的形状或mapTree’
修正参数顺序:
mapTree' :: (a -> b) -> BinaryTree a -> BinaryTree b
mapTree' f bt = foldTree (\x l r -> Node l (f x) r) Leaf bt
---------------------------^
哦,我明白了!所以我在foldTree中的参数排序不符合我对Node的定义。 – m0meni