CONTINUATION PASSING STYLE

Continuation passing style (CPS) is a technique that can be used for the same purpose as accumulator passing style: allowing the implementation of recursive algorithms using tail calls. CPS can often result in rather mind-bending logic, but it can be worth it because you can restructure complex algorithms to use tail calls. The examples in this section are not going to take things too far because the restrictions with tail call optimization mean that recursion in C# will never be the all-encompassing tool it is in full functional languages, but they should be enough to get you started in your own efforts. (There is a lot of information on CPS out there and there’s much you can do with it beyond recursion, if you want to pursue this topic further.)

For a simple introduction, look at this function:

static int Times3(int x) {

  return x * 3;

}

The obvious task that the function performs is that of multiplying the input value by 3. The not-so-obvious task is in the return statement. Implementing a function this way is so natural that you almost don’t notice yourself doing it, but the step of returning the value with a return statement has consequences to the overall structure of algorithm implementation. For instance, to calculate the result of 5 times 3 and output the result on the console, this is what you would do:

Console.WriteLine(Times3(5));

The point is that you’re chaining your calls together by nesting them due to the way return values work syntactically ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.