Lazy evaluation is difficult to combine with imperative features such as exception handling and input/output, because the order of operations becomes indeterminate.
[5] For programming languages, it was independently introduced by Peter Henderson and James H. Morris[6] and by Daniel P. Friedman and David S.
Similarly, for EasilyComputed || LotsOfWork, if the easy part gives True the lots of work expression could be avoided.
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.
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.
[12] 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.
[18] Lazy evaluation can also lead to reduction in memory footprint, since values are created when needed.
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.
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.
For example, consider the following code to lazily compute and print 210: In the above, the variable a initially refers to a lazy integer object created by the lambda expression () -> 1.
Evaluating this lambda expression is similar[a] to constructing a new instance of an anonymous class that implements Lazy
This is an inefficient program because this implementation of lazy integers does not memoize the result of previous calls to eval.
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.
We can build a Java class that memoizes a lazy object as follows:[23][24] This allows the previous example to be rewritten to be far more efficient.
For example, the stream of all Fibonacci numbers can be written, using memoization, as: In Python 2.x the range() function[27] computes a list of integers.