10.3.2.1 using a continuous processing tree
To convert our previously implemented Sumtree function to a continuous version, first, add an extra parameter (continuous) to the function, and then change the way the function returns the result, instead of simply returning the value, and using it as the parameter value for successive calls. Listing 10.18 is the final version of the code.
Listing 10.18 uses contiguous, calculated elements in the tree and (F # Interactive)
> Let rec sumtreecont Tree cont =
Match tree with
| Leaf (NUM), cont (NUM)
| Node (left, right) –>
Sumtreecont Left (Fun leftsum, [1]
Sumtreecont Right (fun rightsum–> [2]
Cont (leftsum + rightsum))); [3]
Val sumtreecont:inttree (INT-a) –> ' a
It is easy to modify the branches of a leaf because it was previously a return value from a leaf. The second case is much more important, and the pattern we use is similar to the previous C # example. We call the function to calculate the and [1] (which is the tail recursion) of the left subtree element, and use the lambda function as its second parameter value. Inside the lambda function, we do something similar to the right subtree [2] (also the tail recursive call). Once we have two sub-tree's and, just take it as an argument, call the original to get the continuous, (this is still tail recursive call).
Another important thing about this function we just wrote is its type signature. In general, we don't need to explicitly write out any type, and F # infers the type for us. This function takes the tree as the first parameter, and continuously as the second parameter. Now, the continuous type is int–> ' A, the overall result of the function is ' A; in other words, the return type of the entire function is the same as the continuous return type.
As we mentioned earlier, in the code, all recursive calls are now tail-recursive, so we can try this function on an unbalanced tree and fail in the previous version:
> Sumtreecont imbalancedtree (Fun r–>
Printfn "Result is:%d" r);;
Result is:8736
Val it:unit = ()
> Sumtreecont imbalancedtree (Fun a-> a);; <--returns from the continuous and
Val It:int = 8736
As you can see, the code now can run very large trees without any hassle. In the first example, we print the result directly in succession and do not return any value in succession, so the overall result of the expression is unit; In the second case, we give it an identity function (the function that returns the value of the parameter) as a continuous. The identity function is already in the F # Library, so we can write the ID. The continuous return type is int, and the value returned from the call to Sumtreecont is the and of all elements in the tree.
10.3.2.1 using a continuous processing tree