Balanced parentheses algorithm in immutable/pure functional Scala with tail-call recursion optimisation

Problem

Algorithm to check parentheses in a String are balanced. This problem is also known as:

  • On Codility: Stacks and Queues: Brackets - Determine whether a given string of parentheses (multiple types) is properly nested.
  • On HackerRank: Balanced Brackets - Given strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES. Otherwise, return NO.

Parentheses in a String are balanced when an opening bracket is followed by another opening bracket or by a closing bracket of the same time.

For example, ([]) is balanced, but ([) and ([)] are not.

Solution

val OpenToClose: Map[Char, Char] = Map('{' -> '}', '[' -> ']', '(' -> ')')

val CloseToOpen: Map[Char, Char] = OpenToClose.map(_.swap)

def parenthesesAreBalanced(s: String): Boolean = {
  if (s.isEmpty) true
  else {
    @scala.annotation.tailrec
    def go(position: Int, stack: List[Char]): Boolean = {
      if (position == s.length) stack.isEmpty
      else {
        val char = s(position)
        val isOpening = OpenToClose.contains(char)
        val isClosing = CloseToOpen.contains(char)
        if (isOpening) go(position + 1, char :: stack)
        else if (isClosing) {
          val expectedCharForMatching = CloseToOpen(char)
          stack match {
            case `expectedCharForMatching` :: rest =>
              go(position + 1, rest)
            case _ =>
              false
          }
        } else false
      }
    }
    go(position = 0, stack = List.empty)
  }
}

Test cases

assert(parenthesesAreBalanced("()"))
assert(parenthesesAreBalanced("[()]"))
assert(parenthesesAreBalanced("{[()]}"))
assert(parenthesesAreBalanced("([{{[(())]}}])"))
assert(!parenthesesAreBalanced("{{[]()}}}}"))
assert(!parenthesesAreBalanced("{{[](A}}}}"))
assert(!parenthesesAreBalanced("{[(])}"))

Scala Concepts

Def Inside Def

A great aspect of Scala is being able to declare functions inside functions, making it possible to reduce repetition.

def exampleDef(input: String): String = {
  def surroundInputWith(char: Char): String = s"$char$input$char"
  surroundInputWith('-')
}
Pattern Matching

Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.

assert("Hello World".collect {
  case character if Character.isUpperCase(character) => character.toLower
} == "hw")

assert("Hello World".filter(Character.isUpperCase).map(_.toLower) == "hw")

assert((1 to 10).collect {
  case num if num % 3 == 0 => "Fizz"
  case num if num % 5 == 0 => "Buzz"
}.toList == List("Fizz", "Buzz", "Fizz", "Fizz", "Buzz"))

Pattern matching is used by methods like Collect, but can also be easily integrated into normal functions.

Pattern matches are effectively "Partial Functions", of type PartialFunction[Input, Output] which is isomorphic to Input => Option[Output]. See Option Type.

Tail Recursion

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

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] = {
  @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)
}

Explanation

Also please find an alternative solution using a foldLeft state machine ParenthesesFoldingStateMachine which makes an advanced streamed implementation possible.

By definition, we need to keep track of the most recent opening bracket, and if the next bracket we approach is a closing bracket that is not the latest bracket, we terminate with a failure, whereas if it is another opening bracket, this is the bracket we consider as the latest, and if it is another closing bracket that matches the latest opening bracket, the new latest opening bracket is 'popped'. This description is enough to suggest to us that we should use a 'stack' structure, and implement our logic as described.

In Scala, a List is equivalent to a stack, it is a structure in the form List[T] = ::(head: T, tail: List[T]) | Nil

We could solve this problem in a standard mutable style, but this would not be the immutable Scala way of doing things.