我正在使用二叉树进行练习:
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)
现在我尝试使用fold:
重写旧的地图功能mapTree' :: (a -> b) -> BinaryTree a -> BinaryTree b
mapTree' f bt = foldTree (\l x r -> Node l (f x) r) Leaf bt
然而,它告诉我上面的lambda中的x
是BinaryTree类型
x :: BinaryTree b (bound at app/Main.hs:85:30)
我很困惑,因为如果我在:t Node
ghci
Node :: BinaryTree a -> a -> BinaryTree a -> BinaryTree a
我得到了:
x
因此,我认为a
应该是Node
类型,因为它位于$query=$_POST["query"];
$matchType=isset($_POST["match_type"])? $_POST["match_type"]:MatchType::CONTAINS;
processRequest($query,$matchType);
构造函数的中间位置。
我哪里出错了?
答案 0 :(得分:2)
将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
---------------------------^