12 Functional iteration

 
Image

In this chapter

  • Learn the three functional tools, map(), filter(), and reduce().
  • 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

  1. There are very similar function implementations.
  2. The names of the functions indicate the difference in implementation.

MegaMart is creating a communications team

Deriving map() from examples

Functional tool: map()

Three ways to pass a function

Example: Email addresses of all customers

Deriving filter() from examples

Functional tool: filter()

Example: Customers with zero purchases

Deriving reduce() from examples

Functional tool: reduce()

Example: Concatenating strings

Things you can do with reduce()

Three functional tools compared

Conclusion

Summary

Up next…

sitemap