function g(h) { return function(y) { return h(h(y)); }; }
81 === g(function(x) { return x * x; })(3);
Specifically, why is this allowed and where can I go read about it?
return h(h(y));
function g(h) { return function(y) { return h(h(y)); }; }
81 === g(function(x) { return x * x; })(3);
Specifically, why is this allowed and where can I go read about it?
return h(h(y));
- That you can use the name of a variable, h, as if it was a function? That's because Javascript has first class functions [1] - the language is defined to support passing them around as variables and calling them like that.
- That you can use h at all even though it's neither a local variable nor a parameter of the anonymous function? That's because functions in javascript aren't simply procedures in the traditional sense - i.e. description (function signature) + code - they are also closures [2]. If you declare one function inside another, it can capture (have a reference to) variables and parameters of the outer one. You are also guaranteed that local variables and parameters will not get cleaned up while a closure still exists that holds a reference to them.
[1] : http://en.wikipedia.org/wiki/First_class_function
[2] : Can't vouch for any particular article, try googling Javascript closures
So, in Javascript, variables can be functions. Which means you can pass in a function as a variable to another function. And the part that says h(h(y)), basically says that "h" has to be a function. Which means you pass in a function, and then it get's applied to itself in the way specified within that function, "g".
Another odd part is the function you pass in:
g(function(x) {
return x * x;
})(3);
because you are passing in a function, but I'd assumed that if you can only pass in one variable, and that variable has to be a function, then it seemed like you wouldn't be able to pass in an initial value for the function you want to apply. But I guess in Javascript you can pass in a value for an anonymous function defined inside a function call by using this syntax: g(function(x) {
whatever it is that happens in this function;
})(some_value_to_be_passed_into_the_previously_defined_anonymous_function); var powerOfFour = g(function(x) {return x*x;});
powerOfFour(3) === 81; //true function callTwice(aFunction) {
return function(y) {
return aFunction(aFunction(y));
};
}
function square(x) { return x*x; }
var squareTwice = callTwice(square);
81 === squareTwice(3);Also, the names you gave don't help at all, as the idea of calling those g and h is to treat them anonymously. By calling it "callTwice", you are thinking about it as some sort of utility function, which is not the case. Shows you didn't grasped the idea behind it yet.
In F# I would certainly call it "callTwice" too:
let callTwice aFunction y = aFunction (aFunction y)