1

Specifying the question I would like to know if there is indeed a series of unambiguous steps to convert recursive functions to tail-recursive functions; maybe by creating auxiliary helper functions if necessary.

If I was not clear in the above question, here is an example of a non-tail-recursive and an equivalent tail-recursive function:

int factorial (int x) {
  if (x == 1) {
    return 1;
  }
  int y = factorial (x-1);
  return x * y;
}

int factorial_tailrec (int acc, int x) {
  if (x == 0) {
    return acc;
  }  
  return factorial_tailrec (acc * x, x-1);
}
Stef
  • 13,242
  • 2
  • 17
  • 28
Wozywors
  • 59
  • 6
  • 1
    Your factorial example uses the associative property of multiplication. Without that, the `acc` parameter would have to be a list. – Matt Timmermans Nov 27 '20 at 13:29

0 Answers0