Code for exercise in Functional Programming in Scala book