Compose function
Compose function
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
Write a function compose
which takes as arguments two functions f and g taking one argument each and returns a function which takes one argument x and returns f(g(x)). Demonstrate that function by calculating both compose(f,g)
and compose(g,f)
with the functions f(x) = x+1 and g(x) = 2x, and applying both functions to the number 7. In the first case, the result should be 15, in the second case, it should be 16.
JavaScript
<lang javascript> function compose(f,g) {
return new Function("x", "return "+f+"("+g+"(x))");
}
function f(a) {
return a+1;
}
function g(a) {
return 2*a;
}
alert("compose(f,g)(7) = "+compose(f,g)(7)); alert("compose(g,f)(7) = "+compose(g,f)(7)); </lang>