Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monad instance for binary tree

I built binary tree with:

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

How can i make Monad type class instance for this tree? And can i make it on not?

i try:

instance Monad Tree where
    return x = Node x Empty Empty 
    Empty >>= f = Empty
    (Node x Empty Empty) >>= f = f x 

But i can't make (>>=) for Node x left right.

Thank you.

like image 458
0xAX Avatar asked Jul 23 '11 06:07

0xAX


1 Answers

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.

like image 91
Edward Kmett Avatar answered Sep 24 '22 03:09

Edward Kmett