I think the Christian answer is good - the continuation of the walkthrough style is just (not so) a simple mechanical transformation that you do in the source code. It may be easier to see when you do this step by step:
1) Start with the source code (here I change the code to only one operation per line):
let rec sumTree tree = match tree with | Leaf(n) -> n | Node(left, right) -> let leftSum = sumTree left let rightSum = sumTree right leftSum + rightSum
2) Add a continuation parameter and call it instead of returning the result (this is still not tail recursive). To perform this type checking, I added a continuation of fun x -> x for both subheadings, so that they simply return the sum as a result:
let rec sumTree tree cont = match tree with | Leaf(n) -> cont n | Node(left, right) -> let leftSum = sumTree left (fun x -> x) let rightSum = sumTree right (fun x -> x) cont (leftSum + rightSum)
3) Now we change the first recursive call to use the continue transmission style - raise the rest of the body to continue:
let rec sumTree tree cont = match tree with | Leaf(n) -> cont n | Node(left, right) -> sumTree left (fun leftSum -> let rightSum = sumTree right (fun x -> x) cont (leftSum + rightSum) )
4) And repeat the same for the second recursive call:
let rec sumTree tree cont = match tree with | Leaf(n) -> cont n | Node(left, right) -> sumTree left (fun leftSum -> sumTree right (fun rightSum -> cont (leftSum + rightSum) ))
source share