Lazy evaluation explained

In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (by the use of sharing).[1]

The benefits of lazy evaluation include:

Lazy evaluation is often combined with memoization, as described in Jon Bentley's Writing Efficient Programs.[2] After a function's value is computed for that parameter or set of parameters, the result is stored in a lookup table that is indexed by the values of those parameters; the next time the function is called, the table is consulted to determine whether the result for that combination of parameter values is already available. If so, the stored result is simply returned. If not, the function is evaluated, and another entry is added to the lookup table for reuse.

Lazy evaluation is difficult to combine with imperative features such as exception handling and input/output, because the order of operations becomes indeterminate.

The opposite of lazy evaluation is eager evaluation, sometimes known as strict evaluation. Eager evaluation is the evaluation strategy employed in most programming languages.

History

Lazy evaluation was introduced for lambda calculus by Christopher Wadsworth and employed by the Plessey System 250 as a critical part of a Lambda-Calculus Meta-Machine, reducing the resolution overhead for access to objects in a capability-limited address space.[3] For programming languages, it was independently introduced by Peter Henderson and James H. Morris and by Daniel P. Friedman and David S. Wise.

Applications

Delayed evaluation is used particularly in functional programming languages. When using delayed evaluation, an expression is not evaluated as soon as it gets bound to a variable, but when the evaluator is forced to produce the expression's value. That is, a statement such as x = expression; (i.e. the assignment of the result of an expression to a variable) clearly calls for the expression to be evaluated and the result placed in x, but what actually is in x is irrelevant until there is a need for its value via a reference to x in some later expression whose evaluation could itself be deferred, though eventually the rapidly growing tree of dependencies would be pruned to produce some symbol rather than another for the outside world to see.[4]

Control structures

Lazy evaluation allows control structures to be defined normally, and not as primitives or compile-time techniques. For example, one can define if-then-else and short-circuit evaluation operators:[5] [6]

ifThenElse True b c = bifThenElse False b c = c

-- orTrue || b = TrueFalse || b = b

-- andTrue && b = bFalse && b = False

These have the usual semantics, i.e., evaluates (a), then if and only if (a) evaluates to true does it evaluate (b), otherwise it evaluates (c). That is, exactly one of (b) or (c) will be evaluated. Similarly, for, if the easy part gives True the lots of work expression could be avoided. Finally, when evaluating, if SafeToTry is false there will be no attempt at evaluating the Expression.

Conversely, in an eager language the above definition for would evaluate (a), (b), and (c) regardless of the value of (a). This is not the desired behavior, as (b) or (c) may have side effects, take a long time to compute, or throw errors. It is usually possible to introduce user-defined lazy control structures in eager languages as functions, though they may depart from the language's syntax for eager evaluation: Often the involved code bodies need to be wrapped in a function value, so that they are executed only when called.

Working with infinite data structures

Delayed evaluation has the advantage of being able to create calculable infinite lists without infinite loops or size matters interfering in computation. The actual values are only computed when needed. For example, one could create a function that creates an infinite list (often called a stream) of Fibonacci numbers. The calculation of the n-th Fibonacci number would be merely the extraction of that element from the infinite list, forcing the evaluation of only the first n members of the list.[7] [8]

Take for example this trivial program in Haskell:

numberFromInfiniteList :: Int -> IntnumberFromInfiniteList n = infinity !! n - 1 where infinity = [1..]

main = print $ numberFromInfiniteList 4

In the function, the value of is an infinite range, but until an actual value (or more specifically, a specific value at a certain index) is needed, the list is not evaluated, and even then, it is only evaluated as needed (that is, until the desired index.) Provided the programmer is careful, the program completes normally. However, certain calculations may result in the program attempting to evaluate an infinite number of elements; for example, requesting the length of the list or trying to sum the elements of the list with a fold operation would result in the program either failing to terminate or running out of memory.

As another example, the list of all Fibonacci numbers can be written in the programming language Haskell as:[8]

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

In Haskell syntax, ":" prepends an element to a list, tail returns a list without its first element, and zipWith uses a specified function (in this case addition) to combine corresponding elements of two lists to produce a third.[7]

Other uses

In computer windowing systems, the painting of information to the screen is driven by expose events which drive the display code at the last possible moment. By doing this, windowing systems avoid computing unnecessary display content updates.[9]

Another example of laziness in modern computer systems is copy-on-write page allocation or demand paging, where memory is allocated only when a value stored in that memory is changed.[9]

Laziness can be useful for high performance scenarios. An example is the Unix mmap function, which provides demand driven loading of pages from disk, so that only those pages actually touched are loaded into memory, and unneeded memory is not allocated.

MATLAB implements copy on edit, where arrays which are copied have their actual memory storage replicated only when their content is changed, possibly leading to an out of memory error when updating an element afterwards instead of during the copy operation.[10]

Performance

The number of beta reductions to reduce a lambda term with call-by-need is no larger than the number needed by call-by-value or call-by-name reduction.[11] [12] And with certain programs the number of steps may be much smaller, for example a specific family of lambda terms using Church numerals take an infinite amount of steps with call-by-value (i.e. never complete), an exponential number of steps with call-by-name, but only a polynomial number with call-by-need. Call-by-need embodies two optimizations - never repeat work (similar to call-by-value), and never perform unnecessary work (similar to call-by-name).[13] Lazy evaluation can also lead to reduction in memory footprint, since values are created when needed.[14]

In practice, lazy evaluation may cause significant performance issues compared to eager evaluation. For example, on modern computer architectures, delaying a computation and performing it later is slower than performing it immediately. This can be alleviated through strictness analysis.[13] Lazy evaluation can also introduce memory leaks due to unevaluated expressions.[15]

Implementation

Some programming languages delay evaluation of expressions by default, and some others provide functions or special syntax to delay evaluation. In Miranda and Haskell, evaluation of function arguments is delayed by default. In many other languages, evaluation can be delayed by explicitly suspending the computation using special syntax (as with Scheme's "delay" and "force" and OCaml's "lazy" and "Lazy.force") or, more generally, by wrapping the expression in a thunk. The object representing such an explicitly delayed evaluation is called a lazy future. Raku uses lazy evaluation of lists, so one can assign infinite lists to variables and use them as arguments to functions, but unlike Haskell and Miranda, Raku does not use lazy evaluation of arithmetic operators and functions by default.[4]

Laziness and eagerness

Controlling eagerness in lazy languages

In lazy programming languages such as Haskell, although the default is to evaluate expressions only when they are demanded, it is possible in some cases to make code more eager—or conversely, to make it more lazy again after it has been made more eager. This can be done by explicitly coding something which forces evaluation (which may make the code more eager) or avoiding such code (which may make the code more lazy). Strict evaluation usually implies eagerness, but they are technically different concepts.

However, there is an optimisation implemented in some compilers called strictness analysis, which, in some cases, allows the compiler to infer that a value will always be used. In such cases, this may render the programmer's choice of whether to force that particular value or not, irrelevant, because strictness analysis will force strict evaluation.

In Haskell, marking constructor fields strict means that their values will always be demanded immediately. The seq function can also be used to demand a value immediately and then pass it on, which is useful if a constructor field should generally be lazy. However, neither of these techniques implements recursive strictness—for that, a function called deepSeq was invented.

Also, pattern matching in Haskell 98 is strict by default, so the [[Tilde#Computer_languages|~]] qualifier has to be used to make it lazy.[16]

Simulating laziness in eager languages

Java

In Java, lazy evaluation can be done by using objects that have a method to evaluate them when the value is needed. The body of this method must contain the code required to perform this evaluation. Since the introduction of lambda expressions in Java SE8, Java has supported a compact notation for this. The following example generic interface provides a framework for lazy evaluation:[17] [18] interface Lazy

The Lazy interface with its eval method is equivalent to the Supplier interface with its get method in the java.util.function library.[19] [20]

Each class that implements the Lazy interface must provide an eval method, and instances of the class may carry whatever values the method needs to accomplish lazy evaluation. For example, consider the following code to lazily compute and print 210:Lazy a = -> 1;for (int i = 0; i < 10; i++) System.out.println("a = " + a.eval);

In the above, the variable initially refers to a lazy integer object created by the lambda expression -> 1. Evaluating this lambda expression is similar to constructing a new instance of an anonymous class that implements Lazy<Integer> with an method returning .

Each iteration of the loop links to a new object created by evaluating the lambda expression inside the loop. Each of these objects holds a reference to another lazy object,, and has an method that calls b.eval twice and returns the sum. The variable is needed here to meet Java's requirement that variables referenced from within a lambda expression be effectively final.

This is an inefficient program because this implementation of lazy integers does not memoize the result of previous calls to . It also involves considerable autoboxing and unboxing. What may not be obvious is that, at the end of the loop, the program has constructed a linked list of 11 objects and that all of the actual additions involved in computing the result are done in response to the call to a.eval on the final line of code. This call recursively traverses the list to perform the necessary additions.

We can build a Java class that memoizes a lazy object as follows:class Memo implements Lazy

This allows the previous example to be rewritten to be far more efficient. Where the original ran in time exponential in the number of iterations, the memoized version runs in linear time:Lazy a = -> 1;for (int i = 0; i < 10; i++) System.out.println("a = " + a.eval);

Java's lambda expressions are just syntactic sugar. Anything that can be written with a lambda expression can be rewritten as a call to construct an instance of an anonymous inner class implementing the interface, and any use of an anonymous inner class can be rewritten using a named inner class, and any named inner class can be moved to the outermost nesting level.

JavaScript

In JavaScript, lazy evaluation can be simulated by using a generator. For example, the stream of all Fibonacci numbers can be written, using memoization, as:/** * Generator functions return generator objects, which reify lazy evaluation. * @return A non-null generator of integers. */function* fibonacciNumbers

let stream = fibonacciNumbers; // create a lazy evaluated stream of numberslet first10 = Array.from(new Array(10), => stream.next.value); // evaluate only the first 10 numbersconsole.log(first10); // the output is [0n, 1n, 1n, 2n, 3n, 5n, 8n, 13n, 21n, 34n]

Python

In Python 2.x the range function[21] computes a list of integers. The entire list is stored in memory when the first assignment statement is evaluated, so this is an example of eager or immediate evaluation:>>> r = range(10)>>> print r[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> print r[3]3

In Python 3.x the range function[22] returns a generator which computes elements of the list on demand. Elements are only generated when they are needed (e.g., when print(r[3]) is evaluated in the following example), so this is an example of lazy or deferred evaluation:

>>> r = range(10)>>> print(r)range(0, 10)>>> print(r[3])3

This change to lazy evaluation saves execution time for large ranges which may never be fully referenced and memory usage for large ranges where only one or a few elements are needed at any time.

In Python 2.x is possible to use a function called xrange which returns an object that generates the numbers in the range on demand. The advantage of xrange is that generated object will always take the same amount of memory.

>>> r = xrange(10)>>> print(r)xrange(10)>>> lst = [x for x in r]>>> print(lst)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

From version 2.2 forward, Python manifests lazy evaluation by implementing iterators (lazy sequences) unlike tuple or list sequences. For instance (Python 2):>>> numbers = range(10)>>> iterator = iter(numbers)>>> print numbers[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> print iterator>>> print iterator.next0

The above example shows that lists are evaluated when called, but in case of iterator, the first element '0' is printed when need arises.

.NET

In the .NET framework, it is possible to do lazy evaluation using the class System.Lazy.[23] The class can be easily exploited in F# using the lazy keyword, while the force method will force the evaluation. There are also specialized collections like Microsoft.FSharp.Collections.Seq that provide built-in support for lazy evaluation. let fibonacci = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (0I,1I)fibonacci |> Seq.nth 1000In C# and VB.NET, the class System.Lazy is directly used. public int SumOr with a more practical example: // recursive calculation of the n'th fibonacci numberpublic int Fib(int n)

public void MainAnother way is to use the yield keyword: // eager evaluation public IEnumerable Fibonacci(int x)

// lazy evaluation public IEnumerable LazyFibonacci(int x)

See main article: Thunk.

See also

Sources

External links

Notes and References

  1. Book: David Anthony Watt. William Findlay. Programming language design concepts. 30 December 2010. 2004. John Wiley and Sons. 978-0-470-85320-7. 367–368.
  2. Bentley, Jon Louis. Writing Efficient Programs. Prentice-Hall, 1985.
  3. Book: Hamer-Hodges . Kenneth . Civilizing Cyberspace: The Fight for Digital Democracy . 1 Jan 2020 . 978-1-95-163044-7 . 410 . BOOK WRITING Incorporated . 29 February 2020.
  4. Casas . A. . Cabeza . D. . Hermenegildo . M.V. . A Syntactic Approach to Combining Functional Notation, Lazy Evaluation, and Higher-Order in LP Systems . Hagiya . M. . P. . Wadler . Functional and logic programming, FLOPS 2006 . 14 January 2011 . 2006 . Springer . 978-3-540-33438-5 . 149 . 10.1007/11737414_11 . Lecture Notes in Computer Science . 3945.
  5. Web site: utility-ht: Data.Bool.HT.Private . hackage.haskell.org . 8 January 2022.
  6. Web site: The Haskell 98 Report: Standard Prelude . www.haskell.org . 8 January 2022 . Boolean functions.
  7. Wells . J.B. . Haack . C. . Branching Types. Daniel . Le Métayer . Programming languages and systems, ESOP 2002 . 2002 . Lecture Notes in Computer Science . 2305 . 10.1007/3-540-45927-8_9 . Springer . 978-3-540-43363-7 . 129–132. free .
  8. Jan-Willem . Maessen . Eager Haskell: resource-bounded execution yields efficient iteration . Proceedings of the 2002 ACM SIGPLAN Haskell Workshop (Haskell '02): Pittsburgh, Pennsylvania, USA; October 3, 2002 . 2002. Association for Computing Machinery. 978-1-58113-605-0. 38–50 See p. 40 . 10.1145/581690.581694.
  9. http://research.microsoft.com/en-us/um/people/blampson/slides/lazyandspeculative.ppt Lazy and Speculative Execution
  10. Web site: Out of memory when assigning values to existing arrays? . MATLAB Answers . MATLAB Central.
  11. Book: Niehren . Joachim . Proceedings of the 23rd ACM SIGPLAN-SIGACT symposium on Principles of programming languages - POPL '96 . Functional computation as concurrent computation . 1996 . 333–343 . 10.1145/237721.237801 . 0897917693 . 7332050 . https://publikationen.sulb.uni-saarland.de/bitstream/20.500.11880/25024/1/RR_95_14.pdf.
  12. Niehren . Joachim . Uniform confluence in concurrent computation . Journal of Functional Programming . September 2000 . 10 . 5 . 453–499 . 10.1017/S0956796800003762 . 66013 . 7 January 2022.
  13. Stelle . George Widgery . Shared-Environment Call-by-Need . July 2019 . 8 January 2022. University of New Mexico. PhD. 11–12.
  14. Book: Chris Smith. Programming F#. 31 December 2010. 22 October 2009. O'Reilly Media, Inc.. 978-0-596-15364-9. 79.
  15. Edward Z. Yang. "Space leak zoo".
  16. Web site: Lazy pattern match - HaskellWiki.
  17. Grzegorz Piwowarek, Leveraging Lambda Expressions for Lazy Evaluation in Java, 4Comprehension, July 25, 2018.
  18. Douglas W. Jones, CS:2820 Notes, Fall 2020, Lecture 25, retrieved Jan. 2021.
  19. https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html Interface Suppier
  20. Book: Bloch, Joshua. "Effective Java: Programming Language Guide" . Addison-Wesley . third . 978-0134685991. 2018.
  21. Web site: 2. Built-in Functions — Python 2.7.11 documentation.
  22. Web site: 2. Built-in Functions — Python 3.5.1 documentation.
  23. Web site: Lazy(T) Class (System). Microsoft.