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))
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
Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.