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(
function() {
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With