First-class functions: Difference between revisions

Content deleted Content added
Added output example
Javascript cleaned up using Scala as an inspiration
Line 952:
 
=={{header|JavaScript}}==
<lang javascript>// Functions as values of a variable
{{incomplete|JavaScript|Fails to demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value}}
var cube = function(x) {
assuming the print function is provided by the environment, like a stand-alone shell. In browsers, use alert(), document.write() or similar
return Math.pow(x, 3);
 
};
<lang javascript>var compose = function (f, g) {
var cuberoot return= function (x) {
return f(gMath.pow(x), 1/3);
};
};
 
// Higher order function
var fn = [Math.sin, Math.cos, function (x) { return Math.pow(x, 3); }];
<lang javascript>var compose = function (f, g) {
var inv = [Math.asin, Math.acos, function (x) { return Math.pow(x, 1/3); }];
( return function (x) {
return f(g(x));
};
};
 
// Storing functions in a array
(function () {
var fun = [Math.sin, Math.cos, cube];
for (var i = 0; i < 3; i++) {
var inv = [Math.asin, Math.acos, function (x) { return Math.pow(x, 1/3); }cuberoot];
var f = compose(inv[i], fn[i]);
print(f(0.5)); // 0.5
}
})();
 
for (var i = 0; i < 3; i++) {
</lang>
// Applying the composition to 0.5
var f = console.log(compose(inv[i], fnfun[i])(0.5));
}</lang>
Output:
<pre>0.5
0.4999999999999999
0.5</pre>
 
=={{header|Lua}}==