12 Functional iteration

In this chapter
- Learn the three functional tools,
map()
,filter()
, andreduce()
. - Discover how to replace simple for loops over arrays with the functional tools.
- Derive implementations for the three functional tools.
Many functional languages come with a variety of powerful, abstract functions for dealing with collections of data. In this chapter, we’re going to focus on three very common ones, namely map()
, filter()
, and reduce()
. These tools form the backbones of many functional programs. They replace for loops as the workhorse of the functional programmer. Since looping over arrays is something we do a lot, these tools are extremely useful.
One code smell and two refactorings
In chapter 10, we learned a code smell and two refactorings that help us eliminate duplication and find better abstractions. They let us create first-class values and higher-order functions. Just as a reminder, here they are again. We’ll apply these new skills throughout the whole of part 2 of this book. Here they are again for reference.
Code smell: Implicit argument in function name
This code smell identifies aspects of code that could be better expressed as first-class values. If you are referring to a value in the body of a function, and that value is named in the function name, this smell applies. The solution is the next refactoring.
Characteristics
- There are very similar function implementations.
- The names of the functions indicate the difference in implementation.