Tail Recursion, a Scala language concept

Last updated

In Scala, tail recursion enables you to rewrite a mutable structure such as a while-loop, into an immutable algorithm.

def fibonacci(n: Int): Int = {
  @scala.annotation.tailrec
  def go(i: Int, previous: Int, beforePrevious: Int): Int =
    if (i >= n) previous else go(i + 1, previous + beforePrevious, previous)

  go(i = 1, previous = 1, beforePrevious = 0)
}

assert(fibonacci(8) == 21)

Tail recursion always has a recursive call in a "final" position, ie you can only either return a result (exit the function), or return another call to self-function

In canonical form, the immutable form gets compiled down to the mutable form,

def evaluateGeneralImmutable[State, Result](initialParams: State)(
    iterate: State => State,
    terminate: State => Boolean,
    extractResult: State => Result
): Result = {
  @scala.annotation.tailrec
  def go(currentParams: State): Result =
    if (terminate(currentParams)) extractResult(currentParams)
    else go(currentParams = iterate(currentParams))

  go(initialParams)
}

becomes (after a stage of compilation):

def evaluateGeneralMutable[State, Result](initialParams: State)(
    iterate: State => State,
    terminate: State => Boolean,
    extractResult: State => Result
): Result = {
  var currentParams: State = initialParams
  while (!terminate(currentParams)) {
    currentParams = iterate(currentParams)
  }
  extractResult(currentParams)
}

This transformation can also be performed the other way round, as to give you a pure immutable solution

What are the benefits of tail recursion?

Tail recursion in Scala utilises a principle known as tail-call optimisation. It allows one to write iterative algorithms (that would otherwise would be complicated while-loops) in immutable form.

What are the benefits of immutability?

It becomes easier to reason about your code, and you always know that you can re-run a function as manytimes as you wish without causing unexpected side effects.

But really, can anything be written in this shape?

Anything that is iterative in nature can, so long as it can be represented in the canonical form.

Let's look at two versions of List#drop(n) - mutable and immutable (Drop, Take, dropRight, takeRight):

def dropMutable[T](list: List[T], n: Int): List[T] = {
  var remaining = n
  var returnList = list
  while (remaining > 0 && returnList.nonEmpty) {
    remaining = remaining - 1
    returnList = returnList.tail
  }
  returnList
}

def dropImmutable[T](list: List[T], n: Int): List[T] = {
  @scala.annotation.tailrec
  def go(remaining: Int, returnList: List[T]): List[T] = {
    if (remaining == 0) returnList
    else
      returnList match {
        case _ :: rest => go(remaining - 1, rest)
        case Nil       => Nil
      }
  }
  go(remaining = n, list)
}

assert(dropMutable(List(1, 2, 3), 2) == List(3))

assert(dropImmutable(List(1, 2, 3), 2) == List(3))

The key thing to notice really is that you move all the `var`s to arguments of the `go` function.

Very detailed advanced example:

Let's try to implement List#foldLeft (foldLeft and foldRight):

Example how to turn a function from mutable to immutable. Warning: a lot of boilerplate code.
def foldLeftMutable[T, S](list: List[T])(initial: S)(f: (S, T) => S): S = {
  var currentResult: S = initial
  var remaining: List[T] = list
  while (remaining.nonEmpty) {
    currentResult = f(currentResult, remaining.head)
    remaining = remaining.tail
  }
  currentResult
}

final case class CurrentState[S, T](
    currentResult: S,
    remainingItems: List[T]
)

def foldLeftMutableSimplified[T, S](
    list: List[T]
)(initial: S)(f: (S, T) => S): S = {
  var currentResult: CurrentState[S, T] =
    CurrentState(currentResult = initial, remainingItems = list)
  while (currentResult.remainingItems.nonEmpty) {
    currentResult = CurrentState(
      currentResult =
        f(currentResult.currentResult, currentResult.remainingItems.head),
      remainingItems = currentResult.remainingItems.tail
    )
  }
  currentResult.currentResult
}

def foldLeftCanonicalMutable[T, S](
    list: List[T]
)(initial: S)(f: (S, T) => S): S = {
  evaluateGeneralMutable(
    CurrentState(currentResult = initial, remainingItems = list)
  )(
    currentResult =>
      CurrentState(
        currentResult =
          f(currentResult.currentResult, currentResult.remainingItems.head),
        remainingItems = currentResult.remainingItems.tail
      ),
    _.remainingItems.isEmpty,
    _.currentResult
  )
}

def foldLeft[T, S](list: List[T])(initial: S)(f: (S, T) => S): S =
  evaluateGeneralImmutable[CurrentState[S, T], S](
    CurrentState(initial, list)
  )(
    iterate = currentState =>
      CurrentState(
        currentResult =
          f(currentState.currentResult, currentState.remainingItems.head),
        remainingItems = currentState.remainingItems.tail
      ),
    terminate = _.remainingItems.isEmpty,
    extractResult = _.currentResult
  )

def foldLeftInlined[T, S](list: List[T])(initial: S)(f: (S, T) => S): S = {
  type State = CurrentState[S, T]
  type Result = S

  val initialParams: State = CurrentState(initial, list)
  val iterate: State => State = currentState =>
    CurrentState(
      currentResult =
        f(currentState.currentResult, currentState.remainingItems.head),
      remainingItems = currentState.remainingItems.tail
    )
  val terminate: State => Boolean = _.remainingItems.isEmpty
  val extractResult: State => Result = _.currentResult
  @scala.annotation.tailrec
  def go(currentParams: State): Result =
    if (terminate(currentParams)) extractResult(currentParams)
    else go(currentParams = iterate(currentParams))

  go(initialParams)
}

def foldLeftInlinedFurther[T, S](
    list: List[T]
)(initial: S)(f: (S, T) => S): S = {
  type State = CurrentState[S, T]
  type Result = S

  @scala.annotation.tailrec
  def go(currentParams: State): Result =
    if (currentParams.remainingItems.isEmpty) currentParams.currentResult
    else
      go(currentParams = {
        val currentState = currentParams
        CurrentState(
          currentResult =
            f(currentState.currentResult, currentState.remainingItems.head),
          remainingItems = currentState.remainingItems.tail
        )
      })

  go(CurrentState(initial, list))
}

def foldLeftInlinedState[T, S](
    list: List[T]
)(initial: S)(f: (S, T) => S): S = {

  @scala.annotation.tailrec
  def go(currentResult: S, remainingItems: List[T]): S =
    if (remainingItems.isEmpty) currentResult
    else
      go(
        currentResult = f(currentResult, remainingItems.head),
        remainingItems = remainingItems.tail
      )

  go(initial, list)
}

def foldLeftCompact[T, S](list: List[T])(initial: S)(f: (S, T) => S): S = {

  @scala.annotation.tailrec
  def go(currentResult: S, remainingItems: List[T]): S =
    remainingItems match {
      case head :: tail =>
        go(currentResult = f(currentResult, head), remainingItems = tail)
      case Nil => currentResult
    }

  go(initial, list)
}

Scala Algorithms: The most comprehensive library of algorithms in standard pure-functional Scala

Think in Scala & master the highest paid programming language in the US

Scala is used at many places, such as AirBnB, Apple, Bank of America, BBC, Barclays, Capital One, Citibank, Coursera, eBay, JP Morgan, LinkedIn, Morgan Stanley, Netflix, Singapore Exchange, Twitter.

Study our 92 Scala Algorithms: 6 fully free, 74 published & 18 upcoming

Fully unit-tested, with explanations and relevant concepts; new algorithms published about once a week.

  1. Compute the length of longest valid parentheses
  2. Check a binary tree is balanced
  3. Make a queue using stacks (Lists in Scala)
  4. Find height of binary tree
  5. Single-elimination tournament tree
  6. Quick Sort sorting algorithm in pure immutable Scala
  7. Find minimum missing positive number in a sequence
  8. Least-recently used cache (LRU)
  9. Count pairs of a given expected sum
  10. Compute a Roman numeral for an Integer, and vice-versa
  11. Compute keypad possibilities
  12. Matching parentheses algorithm with foldLeft and a state machine
  13. Traverse a tree Breadth-First, immutably
  14. Read a matrix as a spiral
  15. Remove duplicates from a sorted list (state machine)
  16. Merge Sort: stack-safe, tail-recursive, in pure immutable Scala, N-way
  17. Longest increasing sub-sequence length
  18. Reverse first n elements of a queue
  19. Binary search a generic Array
  20. Merge Sort: in pure immutable Scala
  21. Make a queue using Maps
  22. Is an Array a permutation?
  23. Count number of contiguous countries by colors
  24. Add numbers without using addition (plus sign)
  25. Tic Tac Toe MinMax solve
  26. Run-length encoding (RLE) Encoder
  27. Print Alphabet Diamond
  28. Balanced parentheses algorithm with tail-call recursion optimisation
  29. Reverse a String's words efficiently
  30. Count number of changes (manipulations) needed to make an anagram with foldLeft and a MultiSet
  31. Count passing cars
  32. Establish execution order from dependencies
  33. Counting inversions of a sequence (array) using a Merge Sort
  34. Longest common prefix of strings
  35. Check if an array is a palindrome
  36. Check a directed graph has a routing between two nodes (depth-first search)
  37. Compute nth row of Pascal's triangle
  38. Run-length encoding (RLE) Decoder
  39. Check if a number is a palindrome
  40. In a range of numbers, count the numbers divisible by a specific integer
  41. Find the index of a substring ('indexOf')
  42. Reshape a matrix
  43. Compute modulo of an exponent without exponentiation
  44. Closest pair of coordinates in a 2D plane
  45. Find the contiguous slice with the minimum average
  46. Compute maximum sum of subarray (Kadane's algorithm)
  47. Pure-functional double linked list
  48. Binary search in a rotated sorted array
  49. Check if a directed graph has cycles
  50. Rotate Array right in pure-functional Scala - using an unusual immutable efficient approach
  51. Check a binary tree is a search tree
  52. Length of the longest common substring
  53. Tic Tac Toe board check
  54. Find an unpaired number in an array
  55. Check if a String is a palindrome
  56. Count binary gap size of a number using tail recursion
  57. Remove duplicates from a sorted list (Sliding)
  58. Monitor success rate of a process that may fail
  59. Find sub-array with the maximum sum
  60. Find the minimum absolute difference of two partitions
  61. Find maximum potential profit from an array of stock price
  62. Fibonacci in purely functional immutable Scala
  63. Fizz Buzz in purely functional immutable Scala
  64. Find combinations adding up to N (non-unique)
  65. Make a binary search tree (Red-Black tree)
  66. Remove duplicates from an unsorted List
  67. Find combinations adding up to N (unique)
  68. Count factors/divisors of an integer
  69. Compute single-digit sum of digits
  70. Traverse a tree Depth-First
  71. Reverse bits of an integer
  72. Find k closest elements to a value in a sorted Array
  73. QuickSelect Selection Algorithm (kth smallest item/order statistic)
  74. Rotate a matrix by 90 degrees clockwise

Explore the 21 most useful Scala concepts

To save you going through various tutorials, we cherry-picked the most useful Scala concepts in a consistent form.

  1. Class Inside Class
  2. Class Inside Def
  3. Collect
  4. Def Inside Def
  5. Drop, Take, dropRight, takeRight
  6. foldLeft and foldRight
  7. For-comprehension
  8. Lazy List
  9. Option Type
  10. Ordering
  11. Partial Function
  12. Pattern Matching
  13. Range
  14. scanLeft and scanRight
  15. Sliding / Sliding Window
  16. Stack Safety
  17. State machine
  18. Tail Recursion
  19. Type Class
  20. View
  21. Zip

Register now (free)