0
\$\begingroup\$

The following tail-recursion example is taken verbatim from Chris Smith's Programming F# 3.0. If this is not the appropriate forum for this post, I will gladly move the post to the appropriate place. I did not post this in SO, because I do not have a problem to solve.

let printListRev list =
    let rec printListRevTR list cont =
        match list with
        // For an empy list, execute the continuation
        | [] -> cont()
        // For other lists, add printing the current
        // node as part of the continuation.
        | hd :: tl ->
            printListRevTR tl (fun () -> printf "%d " hd
                                         cont())

    printListRevTR list (fun () -> printfn "Done!");;
  1. What exactly is cont() continuing. I believe I understand the concept that cont() is encapsulating the remaining work to be done, but I am still a little confused about what is going on.
  2. This SO post contains use of the keyword loop in @Juliet 's answer. I am confused as to why loop is used in that answer and not used in the example above.
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Unfortunately there isn't a place for this type of question on SE - one of the restrictions on questions here is that they "are not asking for an explanation of someone else's code." I do hope you find the information you want, and as a hint loop and cont are not keywords, but are variable/method names. Tail-call recursion is a hard concept to understand, especially if you're new to F#. \$\endgroup\$ Commented Jun 27, 2017 at 20:05
  • 1
    \$\begingroup\$ Welcome to CodeReview. Unfortunately, questions about someone else's code are off-topic. I would post that question on SQ - even if you have no problem. \$\endgroup\$
    – JanDotNet
    Commented Jun 27, 2017 at 20:05

1 Answer 1

3
\$\begingroup\$

cont is continuing the computation process.

The printListRevTR function, in the process of execution, builds up a "chain" of cont functions. The very first (or last, depending on how you count) such function is the one that prints "Done!". After that, each next cont prints the current number and then calls the previous cont.

As printListRevTR goes through the list, it builds up a chain of conts, by creating each next function that calls the previous one. This chain could be visualized like this:

Chain of conts

After the list has been exhausted, the very last iteration calls the very last (or first, depending on how you count) function in that chain, which calls the next one, which calls the next one, and so on, until the final "Done!" function is called.

As for loop - that's not a keyword, just a name that Juliet has chosen for her function.

\$\endgroup\$
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.