Functional Programming in R – what is Lazy evaluation?

Under Lazy evaluation, evaluation of function argument is delayed until necessary. This differs to strict evaluation where the arguments of a function are evaluated before the function is called.

Let’s see an example-

In the first function call, “I am evaluated” is not printed as it is not required to be evaluated. This is also called call-by-promise.

It could be useful when you have parameters which need to be evaluated when only certain conditions are met.

Another example-

Here b is not evaluated until the execution reaches the expression a + b.

Moreover, The expressions you give to function calls are evaluated in the scope outside the function.

Hence the below will give error as it remains unknown when b = a is evaluated as it looks for the value of ain the global scope(outside function f)