Compose function: Difference between revisions
Content added Content deleted
(new task; JavaScript) |
(No difference)
|
Revision as of 15:29, 25 March 2009
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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>