Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Lazy evaluation
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== 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 (object-oriented programming)|constructor]] fields strict means that their values will always be demanded immediately. The <code>seq</code> 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 <code>deepSeq</code> was invented. Also, [[pattern matching]] in Haskell 98 is strict by default, so the <code>[[Tilde#Computer_languages|~]]</code> qualifier has to be used to make it lazy.<ref>{{cite web|url=http://www.haskell.org/haskellwiki/Lazy_pattern_match|title=Lazy pattern match - HaskellWiki}}</ref> === Simulating laziness in eager languages === ====Java==== In [[Java (programming language)|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 [[Anonymous function|lambda expressions]] in Java SE8, Java has supported a compact notation for this. The following example [[Generic classes in Java|generic]] interface provides a framework for lazy evaluation:<ref name="Piwowarek2018">Grzegorz Piwowarek, [https://4comprehension.com/leveraging-lambda-expressions-for-lazy-evaluation-in-java/ Leveraging Lambda Expressions for Lazy Evaluation in Java], [https://4comprehension.com/ 4Comprehension], July 25, 2018.</ref><ref name="Jones2020">Douglas W. Jones, [https://homepage.divms.uiowa.edu/~jones/object/fall20/notes/25.shtml CS:2820 Notes, Fall 2020, Lecture 25], retrieved Jan. 2021.</ref> <syntaxhighlight lang="java"> interface Lazy<T> { T eval(); } </syntaxhighlight> The <code>Lazy</code> interface with its <code>eval()</code> method is equivalent to the <code>Supplier</code> interface with its <code>get()</code> method in the <code>java.util.function</code> library.<ref>[https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html Interface Suppier<T>], retrieved Oct. 2020.</ref><ref name=Bloch>{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}}</ref>{{rp|200}} Each class that implements the <code>Lazy</code> interface must provide an <code>eval</code> 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 2<sup>10</sup>: <syntaxhighlight lang="java"> Lazy<Integer> a = () -> 1; for (int i = 0; i < 10; i++) { Lazy<Integer> b = a; a = () -> b.eval() + b.eval(); } System.out.println("a = " + a.eval()); </syntaxhighlight> In the above, the variable {{mono|a}} initially refers to a lazy integer object created by the lambda expression <code>() -> 1</code>. Evaluating this lambda expression is similar{{efn|name=Java Lambda|Java lambda expressions are not exactly equivalent to anonymous classes, see [[Anonymous function#Differences compared to Anonymous Classes]]}} to constructing a new instance of an [[anonymous class]] that implements <code>Lazy<Integer></code> with an {{mono|eval}} method returning {{mono|1}}. Each iteration of the loop links {{mono|a}} to a new object created by evaluating the lambda expression inside the loop. Each of these objects holds a reference to another lazy object, {{mono|b}}, and has an {{mono|eval}} method that calls <code>b.eval()</code> twice and returns the sum. The variable {{mono|b}} 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 {{mono|eval}}. It also involves considerable [[Autoboxing|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 <code>a.eval()</code> on the final line of code. This call [[Recursion (computer science)|recursively]] traverses the list to perform the necessary additions. We can build a Java class that memoizes a lazy object as follows:<ref name="Piwowarek2018" /><ref name="Jones2020" /> <syntaxhighlight lang="java"> class Memo<T> implements Lazy<T> { private Lazy<T> lazy; // a lazy expression, eval sets it to null private T memo; // the memorandum of the previous value public Memo(Lazy<T> lazy) { this.lazy = lazy; } public T eval() { if (lazy != null) { memo = lazy.eval(); lazy = null; } return memo; } } </syntaxhighlight> 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]]: <syntaxhighlight lang="java"> Lazy<Integer> a = () -> 1; for (int i = 0; i < 10; i++) { Lazy<Integer> b = a; a = new Memo<Integer>(() -> b.eval() + b.eval()); } System.out.println("a = " + a.eval()); </syntaxhighlight> 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,{{efn|name=Java Lambda}} 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 (computer programming)|generator]]. For example, the [[Stream (computing)|stream]] of all [[Fibonacci numbers]] can be written, using [[memoization]], as: <syntaxhighlight lang="js"> /** * Generator functions return generator objects, which reify lazy evaluation. * @return {!Generator<bigint>} A non-null generator of integers. */ function* fibonacciNumbers() { let memo = [1n, -1n]; // create the initial state (e.g. a vector of "negafibonacci" numbers) while (true) { // repeat indefinitely memo = [memo[0] + memo[1], memo[0]]; // update the state on each evaluation yield memo[0]; // yield the next value and suspend execution until resumed } } let stream = fibonacciNumbers(); // create a lazy evaluated stream of numbers let first10 = Array.from(new Array(10), () => stream.next().value); // evaluate only the first 10 numbers console.log(first10); // the output is [0n, 1n, 1n, 2n, 3n, 5n, 8n, 13n, 21n, 34n] </syntaxhighlight> ====Python==== In [[Python (programming language)|Python]] 2.x the <code>range()</code> function<ref>{{cite web|url=https://docs.python.org/library/functions.html#range|title=2. Built-in Functions — Python 2.7.11 documentation}}</ref> 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: <syntaxhighlight lang="pycon"> >>> r = range(10) >>> print r [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print r[3] 3 </syntaxhighlight> In Python 3.x the <code>range()</code> function<ref>{{cite web|url=https://docs.python.org/py3k/library/functions.html#range|title=2. Built-in Functions — Python 3.5.1 documentation}}</ref> returns a [[Generator (computer programming)|generator]] which computes elements of the list on demand. Elements are only generated when they are needed (e.g., when <code>print(r[3])</code> is evaluated in the following example), so this is an example of lazy or deferred evaluation: <syntaxhighlight lang="pycon"> >>> r = range(10) >>> print(r) range(0, 10) >>> print(r[3]) 3 </syntaxhighlight> :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 <code>xrange()</code> which returns an object that generates the numbers in the range on demand. The advantage of <code>xrange</code> is that generated object will always take the same amount of memory. <syntaxhighlight lang="pycon"> >>> 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] </syntaxhighlight> From version 2.2 forward, Python manifests lazy evaluation by implementing iterators (lazy sequences) unlike tuple or list sequences. For instance (Python 2): <syntaxhighlight lang="pycon"> >>> numbers = range(10) >>> iterator = iter(numbers) >>> print numbers [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print iterator <listiterator object at 0xf7e8dd4c> >>> print iterator.next() 0 </syntaxhighlight> :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 <syntaxhighlight inline lang="csharp">System.Lazy<T></syntaxhighlight>.<ref>{{cite web|url=http://msdn.microsoft.com/de-de/library/vstudio/dd642331.aspx|title=Lazy(T) Class (System)|publisher=Microsoft}}</ref> The class can be easily exploited in [[F Sharp (programming language)|F#]] using the <syntaxhighlight inline lang="fsharp">lazy</syntaxhighlight> keyword, while the <syntaxhighlight inline lang="fsharp">force</syntaxhighlight> method will force the evaluation. There are also specialized collections like <syntaxhighlight inline lang="csharp">Microsoft.FSharp.Collections.Seq</syntaxhighlight> that provide built-in support for lazy evaluation. <syntaxhighlight lang="fsharp"> let fibonacci = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (0I,1I) fibonacci |> Seq.nth 1000 </syntaxhighlight> In C# and VB.NET, the class <syntaxhighlight inline lang="csharp">System.Lazy<T></syntaxhighlight> is directly used. <syntaxhighlight lang="csharp"> public int Sum() { int a = 0; int b = 0; Lazy<int> x = new Lazy<int>(() => a + b); a = 3; b = 5; return x.Value; // returns 8 } </syntaxhighlight> Or with a more practical example: <syntaxhighlight lang="csharp"> // recursive calculation of the n'th fibonacci number public int Fib(int n) { return (n == 1)? 1 : (n == 2)? 1 : Fib(n-1) + Fib(n-2); } public void Main() { Console.WriteLine("Which Fibonacci number do you want to calculate?"); int n = Int32.Parse(Console.ReadLine()); Lazy<int> fib = new Lazy<int>(() => Fib(n)); // function is prepared, but not executed bool execute; if (n > 100) { Console.WriteLine("This can take some time. Do you really want to calculate this large number? [y/n]"); execute = (Console.ReadLine() == "y"); } else execute = true; if (execute) Console.WriteLine(fib.Value); // number is only calculated if needed } </syntaxhighlight> Another way is to use the <syntaxhighlight inline lang="csharp">yield</syntaxhighlight> keyword: <syntaxhighlight lang="csharp"> // eager evaluation public IEnumerable<int> Fibonacci(int x) { IList<int> fibs = new List<int>(); int prev = -1; int next = 1; for (int i = 0; i < x; i++) { int sum = prev + next; prev = next; next = sum; fibs.Add(sum); } return fibs; } // lazy evaluation public IEnumerable<int> LazyFibonacci(int x) { int prev = -1; int next = 1; for (int i = 0; i < x; i++) { int sum = prev + next; prev = next; next = sum; yield return sum; } } </syntaxhighlight> {{Main|Thunk}} {{Expand section|date=May 2011}}
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)