Imagine that you have determined that the tree should be displayed as follows, for example:
<1 # <<2#3> # <4#5>>>
Folding such a tree means replacing each branch node with the actual provided operation, which must be performed with the results of a recursive bend performed for data type components (here, for example, the node of two child nodes, which themselves are each tree), for example, with + , producing
(1 + ((2+3) + (4+5)))
Thus, for the leaves, you just need to take the values inside them, and for the branches recursively apply a fold for each of the two child nodes and combine the two results with the provided function, the one with which the tree is collapsed. ( edit :) When "taking" values from leaves, you can further transform them by applying a unary function. Thus, in general, your collapse will need two user-defined functions: one for the leaves, Lf , and the other for combining the results of the recursive folding of the tree-like components (i.e. branches) of the branch nodes, Br .
Your tree data type could be defined differently, for example, with possibly empty leaves, and with internal nodes that also carry values. Then you will need to specify a default value that will be used instead of empty end nodes, and a three-way combination. However, you must have a fold defined by two functions corresponding to the two cases of determining the data type.
Another difference that needs to be realized is what you add up and how you add it up. Those. you can stack the tree linearly, (1+(2+(3+(4+5)))) == ((1+). (2+). (3+). (4+). (5+)) 0 , or you can add a linear list in the form of a tree, ((1+2)+((3+4)+5)) == (((1+2)+(3+4))+5) . The thing is how to bracket the final "expression" in parentheses. Of course, in the classical approach, the convolution of the structure of an expression follows the structure of the convolution of data; but variations exist . Also note that the union operation may not be strict, and the type of “result” that it consumes / produces can express compound (lists and the like), as well as atomic (numbers and the like) values.
(update 2019-01-26) This repeated bracket is possible if the join operation is associative, for example + : (a 1 +a 2 )+a 3 == a 1 +(a 2 +a 3 ) . The data type, together with such an associative operation and the element "zero" ( a+0 == 0+a == a ) is known as the "monoid", and the concept of folding into a "monoid" is fixed by the Foldable type class.