Compose function: Difference between revisions
Content added Content deleted
(new task; JavaScript) |
(replace with redirect (the example is poor, but consider using bits of the task description and example test code)) |
||
Line 1: | Line 1: | ||
#REDIRECT [[Functional Composition]] |
|||
{{task}} |
|||
Write a function <code>compose</code> 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 <code>compose(f,g)</code> and <code>compose(g,f)</code> 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. |
|||
=={{header|JavaScript}}== |
|||
{{works with|Iceape|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> |
Revision as of 17:14, 25 March 2009
Redirect to: