O'Reilly logo

Scala Puzzlers by Nermin Šerifovic, Andrew Phillips

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Puzzler 6

Arg Arrgh!

Scala's concise syntax and rich set of functional primitives allow you to write powerful one-liners. The complexity of these statements can, however, make it difficult to understand the overall intention, at which point declaring a suitably named helper method is often a good idea.

For instance, assume you need to determine the result of applying a simple "generator" function, f, to an initial value, arg, multiple times. This can be achieved neatly using fold—a natural choice for recursive computations:

  // n applications of f to arg: f(f(...f(arg)))
  val result = (1 to n).foldLeft(arg) { (acc, _) => f(acc) }

This is certainly a concise solution to your problem, but figuring out what exactly this line does will generally ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required