Display list in tree

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, .

+3
2

1)

, , map f a, a - , ยน. f a not map f a.

, :

, , c - , mapmtree . ? mapmtree , . ? map :

mapmtree f (Branch a c) = Branch (f a) (map (mapmtree f) c)

2)

1) map mtree2list c. ยฒ. , concat, .


ยน mapmtree , .

ยฒ mtree2list map, , mtree2list.

+5

, , (a โ†’ a) Tree , .

mapmtree f (Leaf a) = Leaf (f a)
+2

Source: https://habr.com/ru/post/1778370/


All Articles