map and filter
The map
and filter
functions are a key part of a much larger group of functions for dealing with sequences. Of that group, map
is certainly the one you will use the most, and filter
is a close second. Their role is to modify sequences.
They accept one or more sequences as input, and return a sequence: sequence in, sequence out:
In the preceding diagram, we can see map
and filter
working together, where filter
eliminates items from the original list while map
changes them.
The first question to ask when solving a problem involving collections is: "Do I want to obtain a list of values, or a single value?" If the answer is a list, then map
, filter
, or similar functions are what you need. If you need some other kind of value, the solution is probably a reduction of some kind, which we will discuss in the next chapter. But even then, as you break the problem down...