树折叠lambda函数中的类型不正确

时间:2016-03-03 16:43:37

标签: haskell lambda

我正在使用二叉树进行练习:

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); 构造函数的中间位置。

我哪里出错了?

1 个答案:

答案 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
---------------------------^