Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would use explicit lazy evaluation. Here's my implementation of it based on Scheme's take:</p> <pre><code>var delay, lazy, force, promise, promiseForced, promiseRunning; (function () { var getValue = function () { return this.value; }; var RUNNING = {}; var DelayThunk = function (nullaryFunc) { this.value = nullaryFunc; }; DelayThunk.prototype.toString = function () { return "[object Promise]"; }; DelayThunk.prototype.force = function () { if (promiseRunning (this)) { throw new Error ("Circular forcing of a promise."); } var nullaryFunc = this.value; this.value = RUNNING; this.value = nullaryFunc (); this.force = getValue; return this.value; }; var LazyThunk = function (nullaryFunc) { DelayThunk.call (this, nullaryFunc); }; LazyThunk.prototype = new DelayThunk (null); LazyThunk.prototype.constructor = LazyThunk; LazyThunk.prototype.force = function () { var result = DelayThunk.prototype.force.call (this); while (result instanceof LazyThunk) { result = DelayThunk.prototype.force.call (result); } return force (result); }; delay = function (nullaryFunc) { return new DelayThunk (nullaryFunc); }; lazy = function (nullaryFunc) { return new LazyThunk (nullaryFunc); }; force = function (expr) { if (promise (expr)) { return expr.force (); } return expr; }; promise = function (expr) { return expr instanceof DelayThunk; }; promiseForced = function (expr) { return expr.force === getValue || !promise (expr); }; promiseRunning = function (expr) { return expr.value === RUNNING || !promise (expr); }; }) (); </code></pre> <p>Example Syntax:</p> <pre><code>var x = lazy (function () { return expression; }); var y = force (x); var z = delay (function () { return expression; }); var w = force (z); </code></pre> <p>Note values are stored once evaluated, so repeated forcing will not do extra computations.</p> <p>Example usage:</p> <pre><code>function makeThunk (x, y, z) { return lazy (function () { // lots of work done here }); } var thunk = makeThunk (arg1, arg2, arg3); if (condition) { output (force (thunk)); output (force (thunk)); // no extra work done; no extra side effects either } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload