λ Continuation passing style - continuation

======= Algorithm ======= <syntax js> // continuation-passing-style // ret is a continuation function which is passed the square of x function sqrCPS(x, ret) { ret(x * x); } // this function exists purely to highlight the callbacks function log(value) { console.log(value); } // using CPS, sqr takes an additional continuation function as a 2nd argument // this function is passed the return value instead of returning normally sqrCPS(8, log); </syntax> ======= Support ======= <syntax js> // Stubbed console. if (typeof console === "undefined") { console = { log: function() {} }; } </syntax> ======= Tests ======= <syntax js> </syntax> ======= Options ======= <syntax js> { "title":"Continuation passing style - continuation", "height":"280px" } </syntax> ======= Visualisation ======= <syntax html> <html> <head> <style> pre {display:block} </style> <script> function globals(forCloning) { if (forCloning) { return {}; } else { 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>