Compose function

From Rosetta Code
Revision as of 15:29, 25 March 2009 by Ce (talk | contribs) (new task; JavaScript)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Compose function
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

Works with: Iceape version 1.0.9

<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>