Check if a number is a palindrome in pure immutable Scala

Problem

A sequence is a palindrome when it is equal to its reverse, and a number is a palindrome if reversing its digits order yields the same number.

Solution

This solution is available for purchase!

Upon purchase, you will be able to Register an account to access solutions on multiple devices.

We use Stripe for secure payment processing.


Alternatively, get unlimited solutions for $3.99 per month!

'Unlimited Scala Algorithms' gives you access to all solutions!

Test cases

assert(isPalindrome(121))
assert(isPalindrome(0))
assert(isPalindrome(3))
assert(isPalindrome(1221))
assert(!isPalindrome(10))
assert(!isPalindrome(910))
assert(isPalindrome(32323))
assert(!isPalindrome(32324))
assert(!isPalindrome(Int.MaxValue))

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('-')
}
Option Type

The 'Option' type is used to describe a computation that either has a result or does not. In Scala, you can 'chain' Option processing, combine with lists and other data structures. For example, you can also turn a pattern-match into a function that return an Option, and vice-versa!

Some examples:

final case class Page(title: String, mainCategory: Option[String])

val pages = List(
  Page(title = "Tail Recursion", mainCategory = None /** No category **/ ),
  Page(title = "Option", mainCategory = Some("standard library")),
  Page(title = "zip", mainCategory = Some("standard library"))
)

val categories: Set[String] = pages.flatMap(_.mainCategory).toSet

assert(categories == Set("standard library"))

def pageCategory(title: String): Option[String] = {
  for {
    page <- pages.find(_.title == title)
    category <- page.mainCategory
  } yield category
}

def pageCategory2(title: String): Option[String] =
  pages.find(_.title == title).flatMap(_.mainCategory)

def pageCategory3(title: String): Option[String] =
  pages.collectFirst {
    case Page(`title`, mainCategory) => mainCategory
  }.flatten

assert(pageCategory("zip").contains("standard library"))

assert(pageCategory("zip") == Some("standard library"))

assert(pageCategory("zip") == Some("standard library"))

assert(pageCategory2("zip") == pageCategory("zip"))

assert(pageCategory3("zip") == pageCategory("zip"))

assert(List[String]("X").headOption == Some("X"))

assert(List[String]().headOption.isEmpty)

val startWithT: String = Option("Some test") match {
  case Some(value) if value.startsWith("T") => value
  case Some(value)                          => s"T${value}"
  case None                                 => "T"
}

assert(startWithT == "TSome test")
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

This problem is similar to CheckArrayIsAPalindrome and CheckStringIsAPalindromebut the number is not indexable by its digits without performance penalty, meaning we cannot use the same approach as in that solution.

So the approach we take is to reverse the number iteratively in one pass, and then compare the reversed number with the original number

To do this 'iteratively' we use Scala's tail-recursion, pattern matching and Options.

This solution certainly could be smaller by eliminating the auxiliary method, but it is more readable and clearer with the use of the 'Option' type