【问题标题】:Incorrect type in tree folding lambda function树折叠 lambda 函数中的类型不正确
【发布时间】:2016-03-04 00:48:24
【问题描述】:

我正在用二叉树做练习:

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)

我很困惑,因为如果我在ghci 中执行:t Node,我会得到:

Node :: BinaryTree a -> a -> BinaryTree a -> BinaryTree a

所以在我看来x 应该是a 类型,因为它位于Node 构造函数的中间位置。

我哪里做错了?

【问题讨论】:

    标签: haskell lambda


    【解决方案1】:

    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 的定义。
    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    相关资源
    最近更新 更多