Search code examples
scalarecursiontail-recursion

Why is a || go(x) a tail call ins call and 1 + go(x) is not?


I am learning Scala with the use of Functional Programming in Scala book. Its Github companion notes say that a || go(x) is still a tail call-optimised recursion while 1 + go(x) is not. How is that computation different and why can compiler optimise one but not the other?


Solution

  • To explain it more succinctly: for tail recursion, the final operation must be the recursive call.

    In 1 + go(x) the final operation is the addition.

    On the other hand, the || operator is lazy: if a is true the expression a || go(x) just evaluates to true; only if a is false is go(x) evaluated, so go(x) is the final operation, thus it's tail recursive.