Implementing Laziness

http://matt.might.net/articles/implementing-laziness/

For this week’s blog I will be taking a look at an article on matt.might.net called ‘Understand and Implement Laziness with examples in Scala, JavaScript, Swift and Racket’. Within this article, Professor Might explains the concept of ‘laziness’ in programming. Laziness (other than the laziness we all initially think of) means delaying the computation of a value until the value is necessary. There are two interpretations of laziness, by-name and by-need. Using the by-name interpretation, the computation of the value is delayed until necessary and the computation is repeated each time it is used. Compared to by-need interpretation in which the computation of the value is delayed until necessary, and then the result is cached for subsequent users. The article explains how most languages we use today are strict languages, meaning they compute the value of an expression immediately. While other languages such as Haskell and Scala are lazy or can be called lazy if explicitly specified for a given situation of variables or parameters.

Scala, which is strict by default, can use the lazy keyword if explicitly specified. Therefore, it makes it easy to use as an example.

val x = { print (“foo”) ; 10 }

print (“bar”)

print (x)

As the article explains, this will print foo, then bar, then 10. But if we use the lazy keyword, we see that the output changes.

lazy val x = { print (“foo”) ; 10 }

print (“bar”)

print (x)

This will produce the result bar, then foo, then 10. The use of the lazy keyword delays the computation of x until it is actually needed.

Parameters can also be lazy. Some languages allow the definition of explicitly lazy parameters to functions. The parameters are not evaluated until they are used. In lazy languages like Haskell, the parameters are all implicitly by-need.

The use of lazy parameters and variables allow the programmer to save on computing space and loading time by holding off on the creation of complex objects and variables until needed.

Leave a comment