|
| 1 | + |
| 2 | +""" |
| 3 | +The functions `map`, `filter`, and `reduce` are "paradigms of functional |
| 4 | +programming", "a style of programming in which the primary method of |
| 5 | +computation is the application of functions to arguments". |
| 6 | +
|
| 7 | +All three functions take as their first argument a function object, and as |
| 8 | +their second, an iterable object (such as a list). They also all return |
| 9 | +function objects. This makes them higher-order functions (in contrast to |
| 10 | +first-order functions). |
| 11 | +
|
| 12 | +Their purpose is to apply the function to each element in the iterable. |
| 13 | +
|
| 14 | +More info: |
| 15 | +1. https://ocw.tudelft.nl/courses/introduction-to-functional-programming/ |
| 16 | +2. https://www.learnpython.org/en/Map%2C_Filter%2C_Reduce |
| 17 | +3. https://stackabuse.com/map-filter-and-reduce-in-python-with-examples/ |
| 18 | +4. https://en.wikipedia.org/wiki/Higher-order_function |
| 19 | +
|
| 20 | +""" |
| 21 | + |
| 22 | +# The first, `map()`, performs the function on the iterable and returns a |
| 23 | +# "one-to-one" iterable in the form of a map-type object. |
| 24 | + |
| 25 | +pencil_case_contents = ['pencil', 'pen', 'fountain pen', 'felt pen', |
| 26 | + 'ruler', 'eraser', 'highlighter', 'scissors'] |
| 27 | + |
| 28 | +# Let's use the built-in string function to capitalise each element in the list |
| 29 | +mapped = map(str.capitalize, pencil_case_contents) |
| 30 | + |
| 31 | +# Note the lack of parentheses after "str.capitalize"; we're not running |
| 32 | +# that function, just passing its name to `map` so it can run it for us. |
| 33 | + |
| 34 | +# Because `map()` returns a generator object, we cast it to a list for printing |
| 35 | +list_from_mapped = list(mapped) |
| 36 | + |
| 37 | +print(list_from_mapped) |
| 38 | + |
| 39 | +# Had we not cast it to a list and instead simply printed `mapped`, we'd |
| 40 | +# get the address in memory of the generator object itself, as you can see |
| 41 | +# by uncommenting the next line. |
| 42 | + |
| 43 | +# print(mapped) |
0 commit comments