Monad instance for binary tree

前端 未结 1 1964
星月不相逢
星月不相逢 2020-12-24 07:07

I built binary tree with:

data Tree a = Empty 
              | Node a (Tree a) (Tree a)
              deriving (Eq, Ord, Read, Show)

How ca

相关标签:
1条回答
  • 2020-12-24 07:28

    There is no (good) monad for the type you just described, exactly. It would require rebalancing the tree and merging together the intermediate trees that are generated by the bind, and you can't rebalance based on any information in 'a' because you know nothing about it.

    However, there is a similar tree structure

    data Tree a = Tip a | Bin (Tree a) (Tree a)
    

    which admits a monad

    instance Monad Tree where
       return = Tip
       Tip a >>= f = f a
       Bin l r >>= f = Bin (l >>= f) (r >>= f)
    

    I talked about this and other tree structures a year or two back at Boston Haskell as a lead-in to talking about finger trees. The slides there may be helpful in exploring the difference between leafy and traditional binary trees.

    The reason I said there is no good monad, is that any such monad would have to put the tree into a canonical form for a given number of entries to pass the monad laws or quotient out some balance concerns by not exposing the constructors to the end user, but doing the former would require much more stringent reordering than you get for instance from an AVL or weighted tree.

    0 讨论(0)
提交回复
热议问题