Lazy evaluation

from Wikipedia, the free encyclopedia

Lazy evaluation in computer science denotes a type of evaluation of expressions in which the result of the expression to be evaluated is only calculated as far as it is currently needed.

One advantage of such an evaluation strategy is time savings, since function calls can be avoided entirely or at least partially saved. In addition, Lazy Evaluation gives the programmer the ability to use infinite data structures . One disadvantage is the difficult debugging in programs that lazy evaluated. It is often difficult to understand at first glance whether an expression has already been evaluated at a certain point in time. This is particularly problematic when function calls can have a side effect .

A special case that is restricted to logical expressions is the short circuit evaluation , which is also implemented in many non- lazy languages ​​such as C or Java .

example

The following example, written in Haskell , shows an application of Lazy Evaluation .

   squares n = (n*n) : squares (n+1)

The function squarescalculates the infinite list of all square numbers starting at n. The square of 3 could therefore be squares 0 !! 3   calculated using the expression   - thereby getting   l !! x   the element at the position xfrom the list l. Without Lazy Evaluation , the call from would squares 0not terminate. Instead, only the parts that are really needed are calculated. The internal evaluation is shortened as follows:

squares 0 !! 3
0*0 : squares (0+1) !! 3
squares (0+1) !! 2
(0+1)*(0+1) : squares (0+1+1) !! 2

(0+1+1+1)*(0+1+1+1) : squares (0+1+1+1+1) !! 0
(0+1+1+1)*(0+1+1+1)
9

At first glance, the lazy evaluation seems to execute calculations several times here, since squaresthe parameter nis used several times on the right-hand side of the function and an unexecuted calculation is used instead of a value. Since Haskell is a purely functional language , the referential transparency ensures that an expression always has the same result. Thus, each expression only has to be calculated once. Haskell takes advantage of this by internally using a pointer to the calculation ninstead of, for example, on the right-hand side of the function definition . If an expression is calculated at one point in the program, the result is also available at other points. (0+1+1+1)