The assignment is to mirror a tree (so at every level the leftmost child becomes the rightmost etc.).
Data structure:
import Data.List
data Rose a = Node a [Rose a]
deriving (Eq, Show)
what I have come up so far:
mirror :: Rose a -> Rose a
mirror (Node x []) = Node x []
mirror (Node x (y:ys)) = mirror (myReverse y)
--reverses given node children
myReverse :: Rose a -> Rose a
myReverse (Node x y) = Node x (reverse y)
So when I run this code with example:
Main> mirror (Node 1 [Node 11 [Node 111 [], Node 112[]], Node 12 [Node 121[]]])
the function returns me Node 112 [] meaning it gets stuck on the leftmost leaf. Judging by my code it seems to be logical, because I’m not passing the tail of the given node children at y:ys. Somehow I have to be able to reverse all the children of the first children of given node AND pass the tail for the same function. No matter how hard I try I’m not able to achieve this and it looks like I have hit the limit of my logical thinking.
I would avoid thinking about it in small terms like the first child and the rest of the children. Instead, try to see the whole picture.
If we think about this recursively, we can observe that we can mirror a tree by:
You already know how to use
reverse. To apply a functionfto every element in a list, you can usemap f. Try to see if you can use these together to solve it for yourself.Spoiler: