Tail-call recursion

Error problem can be handled by adding a specialized TCO error message, possibly with TCO only triggering on a TCO annotation.

The bigger argument for TCO vs loops is that while TCO always can translate to a loop, the TCO recursive function is easier to read (for people comfortable with recursion) and shorter.

Consider:

fac(n, acc = 1) = 1 == n ? acc : fac (n-1, n*acc)

vs

function fac(n)
acc = 1
for elem in 1:n
acc *= elem
end
return acc
end

with TCO, the former has no performance penalty over the latter, and is terser. This means your code actually ends up being shorter than Python, which can be a selling point (and is an essential advantage of functional style).

Or you just use reductions: prod(1:n).

3 Likes