User Tools

Site Tools


λ Continuation passing style - delayed

======= Algorithm ======= <syntax js> // a continuation is more flexible in its use // here the return continuation is delayed function sqrDelayedCPS(x, ret) { // wrap ret in a closure var sqrX = x * x; // delay the return call setTimeout(function() { ret(sqrX); }, 1000); } // this function exists purely to highlight the callbacks function log(value) { console.log(value); } // the delayed CPS function works in exactly the same way as the CPS function sqrDelayedCPS(9, log); // do something else console.log("hello..."); // pass some time passTime(5000); </syntax> ======= Support ======= <syntax js> // fake setTimeout so that it plays nice with user control of algorithm // for now we ignore the delay value var delayedFns = []; function setTimeout(fn, delay) { delayedFns.push(fn); } function passTime(amount) { for (var i=0; i<delayedFns.length; i++) { delayedFns[i](); } delayedFns = []; } // Stubbed console. if (typeof console === "undefined") { console = { log: function() {} }; }</syntax> ======= Tests ======= <syntax js> </syntax> ======= Options ======= <syntax js> { "title":"Continuation passing style - delayed", "height":"380px" } </syntax> ======= Visualisation ======= <syntax html> <html> <head> <style> pre {display:block} </style> <script> function globals() { return { console: { log:function($ret, $prev, str) { if (typeof str === "undefined") { $ret(undefined, $prev); } else { var msg = document.createElement("pre"); msg.innerHTML = "> " + str; document.body.appendChild(msg); var newPrev = function() { document.body.removeChild(msg); $prev(); } $ret(undefined, newPrev); } } } }; } function update(n, x) { } </script> </head> <body> </body> </html> </syntax>

algorithm/continuation_passing_style-delayed.txt · Last modified: 2015/02/02 08:28 (external edit)