

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Functions As Values
incomplete
2: Anonymous Functions
incomplete
3: First-Class and Higher-Order Functions
incomplete
4: Map
incomplete
5: Filter
incomplete
6: Reduce
incomplete
7: Map, Filter, and Reduce Review
incomplete
8: Zip
incomplete
9: Higher-Order Functions Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Higher-order functions like map, filter, and reduce allow us to avoid stateful iteration and mutation of variables.
Take a look at this imperative code that calculates the factorial of a number:
def factorial(n: int) -> int:
# a procedure that continuously multiplies
# the current result by the next number
result: int = 1
for i in range(1, n + 1):
result *= i
return result
Here's the same factorial function using reduce:
import functools
def factorial(n: int) -> int:
return functools.reduce(lambda x, y: x * y, range(1, n + 1))
In the functional example, we're just combining functions to get the result we want. There's no need to reassign variables or keep track of the program's state in a loop.
A loop is inherently stateful! Depending on which iteration you're on, the i variable has a different value.