The Functional Shape of Loops
Learning to program, it's quite common to come across many resources and code samples that include imperative loops of various sorts (particularly for and while).
Frequently when I see examples that include loops, I cringe. They often include many steps that make them harder to understand because there is so much happening every iteration.
Instead, I much prefer to use a functional approach to iteration. Each step can be converted to an individual function and those functions can be applied to the entire collection to produce a result.
There are several advantages to the functional approach over imperative:
- Named functions are essentially declarative; they describe what will happen rather than how it will happen.
- Splitting functionality into individual functions allows for code reuse.
- Pure functions can easily be tested individually.
