While working through some projecteuler.net problems, I’ve found a quite nice solution to a problem using Scala’s sequence comprehensions.

The problem is this one:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

Firstly, a palindrome number is one that reads both ways:

def pal(a: Int): Boolean =
  a.toString == a.toString.reverse

Then use a sequence comprehension to find all the palindrome products, filtering by the pal function:

def greatestPal(start: Int, end: Int): Int = {
  lazy val pals = for {
    x <- start to end
    y <- start to end
    if pal(x * y)
  } yield x * y

  pals.max
}

Reads nicely, huh?

And then you can get to the answer to this particular problem like this:

greatestPal(100, 999)

// 906609

See it in action here.

This could be optimized, of course. That’s just the tip of the iceberg.