What is lazy evaluation?

‹ What is functional programming? | What are higher order functions? ›

Most programming languages use a process called strict evaluation when calling a function. For example, if we multiply the result of 1+2 with the result of 3+4 (to get 7):

multiply(plus(1, 2), plus(3, 4))

most programming languages will first add 1 + 2 and determine the result is 3, then add 3 + 4 to determine that result is 7, and then finally pass 3 and 7 to multiply()function to get 21.

There is an alternative process called lazy evaluation that is used by default in some functional programing languages, where two objects called thunks are created to represent the expression 1+2 and the expression 3+4 without actually doing the addition. The thunks are passed into multiply(), and the addition will only happen if and when multiply() actually needs the results.

While lazy evaluation is useless in the above example, or even harmful, it can be helpful if the thunks involved take a long time to computer and there's uncertainty about whether they will actually be needed.

Lazy evaluation is also useful because it allows the creation of virtual infinitely large lists that can be passed from function to function without running the computer out of memory.

Subscribe to All Posts - Wesley Tanaka