I'm referring to objects that appear to have state.
OK, the thing that really confused me was during the time I was learning Haskell, this exercise:
Based on a simple binary tree:
Code:
data Tree a = Leaf a | Node a (Tree a) (Tree a)
deriving Show
Create a function label:
Code:
label :: Tree a -> Tree Integer
with this property:
Takes a binary tree as an argument. Creates a mirroring tree that has as its
node values the infix index of the other tree's nodes.
Do this with and without monads.
The non-monadic version is simple enough:
Code:
label_helper :: Tree a -> Integer -> (Integer, Tree Integer)
label_helper (Leaf _) i = ((i + 1), Leaf i)
label_helper (Node _ ol or) i = let
(myi, nl) = label_helper ol i
(reti, nr) = label_helper or (myi + 1)
in (reti, Node myi nl nr)
label :: Tree a -> Tree Integer
label t = snd (label_helper t 0)
For the monadic version, I wanted to make a monad from the tree that behaves like the list monad, i.e. loops the following code over its elements (in infix order):
Code:
instance Monad Tree where
(Leaf v) >>= k = k v
(Node vOld leftOld rightOld) >>= k = let
leftNew = leftOld >>= k
(Leaf vNew) = k vOld
rightNew = rightOld >>= k
in
(Node vNew leftNew rightNew)
return x = Leaf x
Base on this, it would have been easy to do this:
Code:
mlabel t = do
e <- t;
return running_counter
However, I failed both at implementing and understanding the logic behind implementing such a running counter. I know it's possible. I just don't get it.
My mind at least really doesn't work in a functional way, although I love the idea of functional languages.