Understanding
and implementing laziness

Blog Details

At first glance, laziness seems to be about efficiency. In computing, laziness means delaying the computation of a value until the value is necessary.

In reality, laziness is more about expressiveness: laziness allows the expression of programs that would otherwise not terminate.In some languages (like Scala, Swift and Perl), laziness also makes it possible to add new constructs to a language without using macros. Since most languages do not provide support for laziness, this article explores how to implement laziness in languages that support closures. We’ll look at manual transformations from languages that have native support for laziness (Scala) into (1) languages that do not support laziness (JavaScript) and (2) languages that have partial support (Swift). We’ll also use macro-generating macros in Racket to implement native and transparent support for multiple kinds of laziness in a strict language.

quote

Implementing laziness in a language like JavaScript requires modifying both the point of definition and the point of use. The exception to this case is when the computation being suspended already produces a procedure. In this case, we can achieve laziness through eta-expansion at the point of definition. In eta-expansion, a function-producing expression is wrapped in an anonymous function that passes its arguments directly to the expression. Consider an expression exp that evaluates to a function that takes one argument. In JavaScript, the function (x) { return ( exp )(x) } behaves identically to exp, in the absence of side effects in exp and assuming exp terminates. Eta-expansion plays a key role in the derivation of a Y combinator that works in strict languages like JavaScript.

Share :

Leave A Comment.