Using strict evaluation results in code that is easily understandable in terms of execution order, an easier debugging process compared to other evaluation strategies, and the responsibility for code performance being shifted to the programmer, meaning a careful code optimization process is required.
Evaluation strategies in programming
Evaluation strategies are used in programming languages to determine when to evaluate the arguments of a function call and what kind of value to pass to the function. There are many evaluation strategies, but most fall under one of two umbrella categories: Strict and lazy evaluation.
Strict evaluation strategies
- Call-by-value: The most common evaluation strategy that consists of copying the content of the actual parameters into the formal parameters. If the function is able to assign values to its parameters, only its local variable is assigned, meaning anything passed into a function call is unchanged. Call-by-value is not a single evaluation strategy but rather a family in which a function’s arguments is evaluated before being passed to the function. Programming languages such as C, Eiffel, and Common Lisp use a call-by-value strategy.
- Call-by-reference: Another common strategy. Whereas the call-by-value strategy copies the content of the actual parameter to the formal parameter, a call-by-reference strategy copies the address of the actual parameter to the formal one. A function receives an implicit reference to a variable used as an argument rather than a copy of its value. C++ uses the call-by-reference strategy.
Lazy evaluation strategies
- Normal order: An expression is evaluated by repeatedly evaluating the left-most, outer-most reducible expression first.
- Call-by-name: The actual parameter is only evaluated if used inside the function. If a parameter is not used in the function body, it is never evaluated. If it is used several times, it’s re-evaluated each time it appears.
- Call-by-macro-expansion: Similar to call-by-name but avoids substitution. Provides developers with a mechanism to add new syntax to the core language grammar known as macros. Macros are expanded into code by a macro preprocessor.
- Call-by-need: A parameter is evaluated only if it’s used. Once the first evaluation happens, the result is cached, so further uses of the parameter don’t require re-evaluation.