Challenge - Functional chain
Build a text-processing chain with pure functions, composition and currying.
Functional chain
In this challenge you will build a chain of pure functions. Pure functions always return the same output for the same input and have no side effects.
To combine two functions you write compose(f, g); the returned function computes f(g(x)). This is called function composition.
To make a multi-argument function callable step by step you use currying: curryAdd(a) returns a function that takes b and returns a + b.
Exercise Write compose and curryAdd
Write compose(f, g) that returns a function taking x and returning f(g(x)). Then write curryAdd(a) that takes a and returns a function taking b and returning a + b.
Show example solution
Start with function compose(f, g) { return function(x) { return f(g(x)); }; }. Then write function curryAdd(a) { return function(b) { return a + b; }; }.
Example solution:
function compose(f, g) {
return function(x) {
return f(g(x));
};
}
function curryAdd(a) {
return function(b) {
return a + b;
};
}
Test yourself
-
What does compose(f, g)(x) return?
function compose(f, g) { return function(x) { return f(g(x)); }; }- g(f(x))
- f(x) then g(x)
- f(g(x))
- x(f, g)
Show answer
f(g(x)) — Correct! compose(f, g)(x) applies g first, then passes the result to f.
-
Complete the compose function
function compose(f, g) { return function(x) { ____ }; }Show answer
function compose(f, g) { return function(x) { return f(g(x)); }; } -
Match the functional concepts
- compose(f, g)
- computes f(g(x))
- curry(f)
- step-by-step args
- pure function
- no side effects
- higher-order
- returns a function