I'm trying to solve the last exercise of this JavaScript Closure Tutorial which takes about Continuation Passing.
This is the exercise:
Define a function named bothC similar to seqC that takes functions fC and gC and continuations success and failure. The functions fC and gC both just take success and failure continuations. Your function bothC should call both fC and gC no matter what, but only call success if both succeeded, and failure otherwise. Don't forget, your function will never return!
This seems to be a valid answer:
var bothC = function (fC, gC, success, failure) {
fC(
fun开发者_如何学运维ction() {
gC(success, failure);
},
function() {
gC(failure, failure);
}
);
};
But why can't I just do this?
var bothC = function(fC, gC, success, failure) {
fC(gC(success, failure), gC(failure, failure));
}
Any time you have a function followed by parens around an argument set (even if there are no arguments, that is still an arguments set), the message to JS is execute immediately
. This means that gC(success, failure)
actually runs gC and then returns whatever gC would return. fC(gC(success, failure), gC(failure, failure));
basically means, "call fC
with the return of gC(success, failure)
and gC(failure, failure)
as parameters"
In order to prevent this action and still make it callable, you need to wrap it in a function(){}
(it can be anonymous or not). That will make it into a returnable and callable object, instead of simply as a method call. fC(function() {gC(success, failure); }, function() { gC(failure, failure); } );
means, "call fC
with a function which will call gC(success, failure)
and a function which will call gC(failure, failure)
as parameters"
Just as an FYI, the Sussman and Steele showed that continuations and closures, more or less, are the same thing, the difference is basically in syntax (this was in the late '70's. Read Gabriel/Steele History Of Lisp Pg. 33). JS has great closure syntax but, in my opinion, the best example of continuation in a currently popular language is the Python yield
syntax. Just saying.
Because it calls gC
(instead of defering it) and pass its result to fC
.
You code won't work because it will immediately call gC
twice when bothC
is called. fC
is supposed to take two continuations, meaning, they have to be callable functions, not the results of calling functions.
精彩评论