【问题标题】:Binary tree monad implementation二叉树单子实现
【发布时间】:2013-07-06 01:41:59
【问题描述】:

我很难理解如何为二叉树的单子正确实现 (>>=)。我有以下二叉树:

data BinTree a = Leaf a | Node a (BinTree a) (BinTree a) 
    deriving (Eq, Ord, Show, Read) 

这是我的 monad 的 (>>=) 运算符:

Node x l r >>= f = Node (f x) (l >>= f) (r >>= f)
                 __________^

我不断收到此错误:

Couldn't match type `b' with `BinTree b'
`b' is a rigid type variable bound by
  the type signature for
    >>= :: BinTree a -> (a -> BinTree b) -> BinTree b
  at test.hs:153:5
 In the return type of a call of `f'
 In the first argument of `Node', namely `(f x)'
 In the expression: Node (f x) (l >>= f) (r >>= f)

所以我不明白如何才能获得正确类型的正确叶子?

感谢任何帮助

谢谢

【问题讨论】:

    标签: haskell binary-tree monads


    【解决方案1】:

    您对Node 的定义表明构造函数中的第一个值具有 键入a,但您正试图将BinTree a 插入节点值。 您需要做的是绑定f x 的结果并将其用作 新节点。

    (Node x l r) >>= f = f x >>= \y -> Node y (l >>= f) (r >>= f)
    

    【讨论】:

    • 谢谢!没想到绑定结果。
    • IMO,LHS 上的括号使其可读性降低。我更喜欢写这个Node x l r >>= f \n = f x >>= ...
    • 我以同样的方式实现了 Monad 类型类。它编译得很好,但是,在执行这个时,它总是以无限循环结束。从我的角度来看,为这种 Tree 类型实现 Monad 类型类是不可能的。还是我错了?
    猜你喜欢
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 2017-10-05
    • 1970-01-01
    • 2015-07-23
    相关资源
    最近更新 更多