Exercise in functional programming in Scala