Here's how Wikipedia defines function composition:
However you want to solve the first and third point. In short:
Write a function that takes a variable number of function arguments and returns a function that takes a variable number of arguments and returns the result of the successive application of the earlier functions.
I should not be allowed to write stuff like that...
If you're completely new to this, here are a couple of topics you may want to get familiar with beforehand:
For instance, here's a compose function in JavaScript that takes 2 arguments and return the composition of both:In computer science, function composition is an act or mechanism to combine simple functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of each function is passed as the argument of the next, and the result of the last one is the result of the whole.
function compose(f, g) {
return function (x) {
f(g(x));
}
}
function increment(x) {
return x + 1;
}
function square(x) {
return x*x;
}
>>> compose(square, increment) (5)
36
I can find 3 main issues in the compose function I wrote:
- It assumes g is a function that takes one argument.
- It assumes f is a function that takes one argument and that g(x) is of the correct type.
- It can only take 2 arguments. You don't want to end up writing compose(f, compose(g, compose(...
However you want to solve the first and third point. In short:
Write a function that takes a variable number of function arguments and returns a function that takes a variable number of arguments and returns the result of the successive application of the earlier functions.
I should not be allowed to write stuff like that...
If you're completely new to this, here are a couple of topics you may want to get familiar with beforehand:
- Higher order functions.
- Variadic functions.