r/ProgrammingLanguages • • Jan 18 '26

Why not tail recursion?

In the perennial discussions of recursion in various subreddits, people often point out that it can be dangerous if your language doesn't support tail recursion and you blow up your stack. As an FP guy, I'm used to tail recursion being the norm. So for languages that don't support it, what are the reasons? Does it introduce problems? Difficult to implement? Philosophical reasons? Interact badly with other feathers?

Why is it not more widely used in other than FP languages?

76 Upvotes

117 comments sorted by

View all comments

Show parent comment

1

u/j_mie6 Jan 19 '26

It's not always that easy to transform, bear in mind. A good example is Fibonacci:

def fibLoop(n: Int, x: Int, y: Int) =
  if n == 0 then x
  else fibLoop(n-1, y, x+y)

Or whatever. This is, imo, the cleanest you can get (even more so than a loop), but to make that a little more substantiated, consider how to turn it into a loop by the process outlined above:

def fib(m: Int) = {
  var x = 1
  var y = 1
  var n = m
  while (true) {
    if (n == 0) return x
    else {
      n = n - 1
      x = y
      y = x + y
    }
}

Firstly, it's a good deal bigger (subjectively harder to read) and secondly it has a bug in it! The transformation we have to do also needs to account for the fact that the current x and y are the same as the next x and y referentially. You have to introduce a temp variable to store x before x = y. That's definitely non-trivial to keep track of, imo.

2

u/kohugaly Jan 19 '26

It's correct and looks nearly identical when written using tuple assignment.

while(true) {
  if (n ==0) return x
  else (n, x, y) = (n-1, y, x+y)
}

But I concede the point. Not many imperative languages support tuple assignments and it's an easy mistake to make.