[Haskell-cafe] Monad for binary tree data structure

Ivan Lazar Miljenovic ivan.miljenovic at gmail.com
Sat Jul 23 09:21:36 CEST 2011


2011/7/23 Александр <kommunist1917 at mail.ru>:
> Hello,
>
>>1) Do you really need a Monad instance for this?
>
> Only for training purposes.

Then if you _must_ define Monad instances, maybe you should consider
one for a data structure which makes more sense?

> 2) One possibility is just have it being (Node x _ _) >>= f = f x
>
> I've already tried to do so, but i get only 1 element. Look.
>
> I have a function fillTree that's fill this binary tree.
>
> let a = fillTree 1 Empty
>
> a >>= \x -> return (x * 2)
>
> I got:
>
> Node 2 Empty Empty

Well, yes, but that's the fault of your `f' ! ;-)

> But i have tree with 100 elements.

OK, an alternative would be to adapt the approach taken for lists,
which uses a right-fold.  The problem that I see for this is how to
combine the resulting trees from applying ">>= f" recursively on the
right and left sub-trees with the left and right sub-trees in "f x".

-- 
Ivan Lazar Miljenovic
Ivan.Miljenovic at gmail.com
IvanMiljenovic.wordpress.com



More information about the Haskell-Cafe mailing list