I'm attempting to create my own fold function which I can then use on my custom tree.
My Tree is simple like so:
data Stem a = Node (Stem a) (Stem a) | Leaf a
I want to be able to build a foldTree
function which works much in the same way as foldr
would.
I've manage to get it to work for when n=1
or just a leaf
with the following
foldTree :: (x -> u -> u) -> u -> Stem x -> u
foldTree f a (Leaf o) = f o a
But I can't seem to work out the next line (IE for when there are nodes and leafs), I understand I need to recursively call foldTree but I'm not sure how I can do it. I've tried the following but I'm not having much luck.
foldTree f a (Node l r) = f a (foldTree f a l) (foldTree f a r)
This doesn't work as I know my parameters are x -> u -> u
and so I've got one too many parameters. Although this is where I am stuck I'm not sure how to traverse both paths correctly.
So all together I have
foldTree :: (x -> u -> u) -> u -> Stem x -> u
foldTree f a (Leaf o) = f o a
foldTree f a (Node l r) = f a (foldTree f a l) (foldTree f a r) <-- Not working
How can I update this second line (or possibly something else in the method to get it to work?
Thanks for the help!