I need your help in solving the following two functions / problems:
1)
I need to replace items in a tree. A tree branch can have any number of auxiliary branches, as shown below in the code.
data Tree a = Leaf a | Branch a [(Tree a)] deriving (Show)
mapmtree :: (a -> a) -> Tree a -> Tree a
mapmtree f (Leaf a) = (f a)
mapmtree f (Branch a c) = Branch (map f a) (mapmtree f c)
I need to navigate through the elements and change them. My problem is in the last line. The mapmtree function accepts (Tree a), but the branch may have a list of subvections, so it is impossible to compile the above code, as it gives an error. How can I call the mapmtree function on branch subsidiary lists?
This is the error I get when loading it:
Couldn't match expected type `Tree a'
against inferred type `[Tree a]'
In the second argument of `mapmtree', namely `c'
In the second argument of `Branch', namely `(mapmtree f c)'
In the expression: Branch (map f a) (mapmtree f c)
2)
The second question is about turning the tree into a list in depth-first . This is the code that I have now, but I am stuck and do not know how to go further:
data Tree a = Leaf a | Branch a [(Tree a)] deriving (Show)
mtree2list :: Tree a -> [a]
mtree2list (Leaf a) = [a]
mtree2list (Branch a c) = a : (mtree2list c)
. , , , .
, Haskell, .