Functional style

It’s hard to describe exactly what a functional style is, but generally I think it means decomposing a big problem into smaller pieces, then solving each piece with a function or combination of functions. When using a functional style, you strive to decompose components of the problem into isolated functions that operate independently. Each function taken by itself is simple and straightforward to understand; complexity is handled by composing functions in various ways.

The following three chapters discuss the three key functional techniques that help you to decompose problems into smaller pieces:

  • Chapter 9 shows you how to replace many for loops with functionals which are functions (like lapply()) that take another function as an argument. Functionals allow you to take a function that solves the problem for a single input and generalise it to handle any number of inputs. Functionals are by far and away the most important technique and you’ll use them all the time in data analysis.

  • Chapter 10 introduces function factories: functions that create functions. Function factories are less commonly used than functionals, but can allow you to elegantly partition work between different parts of your code.

  • Chapter 11 shows you how to create function operators: functions that take functions as input and produce functions as output. They are like adverbs, because they typically modify the operation of a function.

Collectively, these types of function are called higher-order functions and they fill out a two-by-two table: