Problem #40 in Scala