The tailrec Annotation
Guaranteed optimization.
What is Tail Recursion?
A recursive call is in tail position when it is the very last action of the function. A tail-recursive function can be optimized into a loop, reusing a single stack frame, so it never overflows.
Tail Position
In n * factorial(n-1), the recursive call is not last: the multiplication happens after it returns. In gcd(b, a % b), the call is last. Only the latter is tail-recursive.
All lessons in this course
- Recursion Basics
- The tailrec Annotation
- Accumulator Pattern
- Trampolining