Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lazy evaluation in JavaScript
function delay(expressionAsFunction) {
var result;
var isEvaluated = false;
return function () {
if (!isEvaluated)
result = expressionAsFunction();
return result;
};
}
function force(promise) {
return promise();
}
function cons(car, cdr) {
return [car, cdr];
}
function next(n) {
return cons(n, delay(function () {return next(n + 1);}));
}
function head(stream) {
return stream[0];
}
function tail(stream) {
return force(stream[1]);
}
var stream = next(0);
console.log(stream);
console.log(head(tail(tail(stream)))); //==> 2
@langpavel

This comment has been minimized.

Show comment
Hide comment
@langpavel

langpavel May 7, 2014

Wow, LISP is better readable :-)

But good example ;-)

Wow, LISP is better readable :-)

But good example ;-)

@gavin-romig-koch

This comment has been minimized.

Show comment
Hide comment
@gavin-romig-koch

gavin-romig-koch Jun 9, 2015

Except that you never set isEvaluated, so expressionAsFunction is called every time the promise is forced, not just the first time.

Except that you never set isEvaluated, so expressionAsFunction is called every time the promise is forced, not just the first time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment