Editor

Function Composition

Functions · Advanced · 85 XP · about 8 min

Write a function called compose(f, g) that takes two functions and returns a new function that applies g first, then f.

Mathematically: compose(f, g)(x) = f(g(x))

Example

double = lambda x: x * 2
add_one = lambda x: x + 1

# compose(double, add_one)(5) = double(add_one(5)) = double(6) = 12
composed = compose(double, add_one)
composed(5)  # Returns 12

# compose(add_one, double)(5) = add_one(double(5)) = add_one(10) = 11
composed2 = compose(add_one, double)
composed2(5)  # Returns 11

Requirements

  • Return a new function that first applies g, then f
  • The composed function should accept one argument
def compose(f, g):
# Your code here - return a new function
pass
# Test your function
double = lambda x: x * 2
add_one = lambda x: x + 1
composed = compose(double, add_one)
print(composed(5)) # Should be 12

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.