data Tree a = Tree a [Tree a]
Note that we do not allow empty trees, and that a leaf is a tree with an empty list of subtrees.
treeFold :: (a -> [b] -> b) -> Tree a -> b
treeFold f (Tree x s) = f x (map (treeFold f) s)
Given the above information, I don't understand how the tree fold function returns a result by recursively applying the fold operation to the subtrees, then applying the function to the label at the root and the results returned from the subtrees.
I also do not get how the tree Fold function only takes one argument instead of 2, when it is passed as argument to the map function and it still compiles and runs properly.
For example, the tree size function below, counts the nodes of the tree.
treeSize :: Tree a -> Int
treeSize = treeFold (\x ys -> 1 + sum ys)
So running treeSize tree where tree = Tree 4 [Tree 1 [Tree 2 [], Tree 3 []]] gives the size of the tree as 4.
In the tree size function above, the tree fold function is also passed one argument instead of two. Also, the x that is passed to the tree fold function is not getting used anywhere, so why do you need it there. Removing it causes the program to not compile and it gives the following error message.
Couldn't match type `a' with `[[Int] -> Int]'
`a' is a rigid type variable bound by
the type signature for treeSize :: Tree a -> Int
at treeFold.hs:15:1
In the first argument of `sum', namely `ys'
In the second argument of `(+)', namely `sum ys'
In the expression: 1 + sum ys
Any help would be greatly appreciated.