0

Using functional continuation in ReasonML, can I apply CPS in numeric analysis/method? e.g. euler method, finite difference method.

let factorial3 = n => {
  let rec cont = (n, func) =>
    if (n <= 1) {
      func();
    } else {
      cont(n - 1, () => n * func());
    };
  cont(n, () => 1);
};
madeinQuant
  • 1,721
  • 1
  • 18
  • 29
  • 1
    What does “can” mean? The code you’ve written looks a bit like continuation passing style. If you’re asking if it’s a good idea, the answer is no. – Dan Robertson Feb 29 '20 at 10:26
  • 1
    CPS usually carries state around through arguments of the continuation. That is the whole point of CPS. Here is a runnable [example in JS](https://repl.it/repls/DoubleHelpfulInterfaces). Every recursive algorithm can be encoded in CPS. –  Feb 29 '20 at 11:17

1 Answers1

0

The question has already been answered in the question body. You can apply CPS in Reason for anything that you'd like.

You provided yourself an example of a function using CPS.

One thing I wanted to add is that on your example, it would be preferable to just use an accumulator parameter instead like this:

let factorial = n => {
  let rec cont = (n, tot) =>
    if (n <= 1) {
      tot;
    } else {
      cont(n - 1, n * tot);
    };
  cont(n, 1);
};

as it avoids allocating a new lambda on every recursion while your function remains tail-recursive. I think that CPS would be better left for more involved examples where your have more than one recursive calls per function call but would still like your function to remain tail recursive.

This article contains examples where CPS is a more appropriate tool (written in F#): https://www.gresearch.co.uk/article/advanced-recursion-techniques-in-f/

namesis
  • 157
  • 10