【问题标题】:Foldable binarytree never finishes some foldMap queries?可折叠二叉树永远不会完成一些 foldMap 查询?
【发布时间】:2014-12-11 22:22:49
【问题描述】:

我尝试过让 BinaryTree 可折叠。

这是我的二叉树:

data BinaryTree2 a = Node2 a (BinaryTree2 a) (BinaryTree2 a)
                   | Leaf2
                   deriving Show

然后我尝试通过实现 foldMap 使其可折叠:

import qualified Data.Foldable as F
instance F.Foldable BinaryTree2 where
foldMap f Leaf2 = mempty
foldMap f (Node2 v l r) = f v `mappend` F.foldMap f l `mappend` F.foldMap f r

上面的方法可以编译,但除非可以通过查看第一个节点来回答查询,否则它不起作用。

t3 = Node2 3 (Node2 1 Leaf2 Leaf2) (Node2 5 Leaf2 Leaf2)

foldMap (Any . (== 3)) t3
-- ghc output: Any {getAny = True}

foldMap (All . (== 3)) t3
-- ghc never returns: All {getAll =

我做错了什么?

【问题讨论】:

  • 请包括foldMap,还可能包括treeInsert2preoder 的实现。
  • @AndrásKovács 抱歉;复制粘贴了错误的东西。
  • 它对我有用。与foldMap 的定义是否有重叠?也许F.foldMap 也适合你?
  • 好的,太好了。谢谢你们俩。一定是关于 os x 中的 ghc 的东西(试图让它运行,它只是吃了我所有的记忆)。附言。使用 F.foldMap 的 Sassa 不起作用,但谢谢。
  • Creating an instance of the Fractional Typeclass in Haskell 的可能重复问题或其他有缩进问题的类似问题。

标签: haskell


【解决方案1】:

缩进。这很重要。

instance F.Foldable BinaryTree2 where
  foldMap f Leaf2 = mempty
  foldMap f (Node2 v l r) = f v `mappend` F.foldMap f l `mappend` F.foldMap f r
-- ^^^^^^

您应该很难过您可以使用foldMap 而不是F.foldMap

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2017-01-27
    相关资源
    最近更新 更多