Programming Search⌘K

Conceptintro

Strict evaluation

Also called eager evaluation, applicative-order evaluation, call by value evaluation, greedy evaluation, strictness.

Strict evaluation computes every argument of a function before the function body runs. It is the default in most languages, and the opposite of lazy evaluation.

Applies to
core-languages

Idea

A function call has arguments, and each argument is an expression. Strict evaluation computes the value of every argument first, and only then runs the body of the function. The body receives values, not expressions. This is the rule in Python, Java, C, Go, Rust and almost every other language that programmers use every day:

def trace(label, value):
    print("evaluating", label)
    return value


def first(a, b):
    print("inside first")
    return a


print(first(trace("a", 1), trace("b", 2)))
Output
evaluating a
evaluating b
inside first
1

The function first never uses b, but the program computes it anyway, before first starts. The opposite rule is lazy evaluation, which computes an argument only when the body needs its value.

How it works

Evaluate, then apply. SICP describes two ways to evaluate a call. Normal order substitutes the argument expressions into the body and reduces them later. The other is the "evaluate the arguments and then apply" method that the interpreter actually uses, "which is called applicative-order evaluation."1 Applicative order is the operational name of strict evaluation: the caller reduces each argument to a value, and the call passes the values.

Strict as a property of a function. In semantics, the word strict describes a function, not an evaluator. Let the symbol ⊥, called bottom, stand for a computation that fails or never ends. A function f is strict if f(⊥) = ⊥, that is, if the call fails whenever the argument fails. Wikipedia notes that applicative order "has the effect of making the function strict, i.e. the function's result is undefined if any of the arguments are undefined, so applicative order evaluation is more commonly called strict evaluation."2 In a strict language every function is strict in every argument, because the call never starts when an argument fails.

Strict and eager. The two words often mean the same thing, but they come from two views. Strict is a statement about results: an undefined argument gives an undefined call. Eager is a statement about time: the work happens as soon as the program reaches the expression. The same article states that a call "is performed as soon as it is encountered in a procedure, so it is also called eager evaluation or greedy evaluation."2 A lazy language can still evaluate some arguments eagerly when the compiler can prove that the function is strict in them, and the result does not change.

The view from a lazy language. Haskell is non-strict by default. Its report states that errors, written ⊥, "are indistinguishable by a Haskell program from non-termination. Since Haskell is a non-strict language, all Haskell types include ⊥."3 When a Haskell program needs strict evaluation, it asks for it with seq or with the operator $!, and the report states: "The operator $! is strict (call-by-value) application, and is defined in terms of seq."4 So strict application is the default in most languages, and a library operator in Haskell.

Order inside the strict rule. Strict evaluation says that all arguments are ready before the body runs. It does not say in which order the arguments are computed. Some languages fix the order and others leave it open, so two side effects in two arguments can happen in either order. See order of evaluation.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeArguments are evaluated before the call, and a parameter of a function type such as () -> T is a thunk; no example file because kotlinc is not installed on the machine that records the examples.
SQLDoes not applyA query states the result, and the optimizer decides when and if each part of an expression is evaluated.
BashNative
PowerShellNativeThe arguments of a command are evaluated before the command runs; no example file because pwsh is not installed on the machine that records the examples.
HTMLDoes not applyHTML has no evaluation of expressions.
CSSDoes not applyCSS has no function calls of the kind that this page describes.
Regular expressionsDoes not applyA regular expression has no function calls and no arguments.
Language Verdict Arguments Order of arguments
Python native strict left to right
JavaScript native strict left to right
TypeScript native strict left to right, as JavaScript
Java native strict left to right
Kotlin native strict not covered here
C# native strict left to right
Go native strict calls in left to right order
Rust native strict left to right
C native strict unspecified
C++ native strict indeterminately sequenced
Bash native words are expanded before the command runs left to right
PowerShell native strict not covered here
SQL n/a the optimizer decides none

In all of these languages, the operators && and || and the conditional expression are the exceptions: they evaluate an operand only if the result needs it. See short-circuit evaluation.

Python. The reference states: "All argument expressions are evaluated before the call is attempted."5

Java. The specification states that each argument expression "appears to be fully evaluated before any part of any argument expression to its right."6

Go. Arguments "are evaluated before the function is called", and in an expression "all function calls, method calls, receive operations, and binary logical operations are evaluated in lexical left-to-right order."7

Rust. The operands of a call "are evaluated prior to applying the effects of the expression. Expressions taking multiple operands are evaluated left to right as written in the source code."8

C#. "The expressions of an argument list are always evaluated in textual order."9

JavaScript and TypeScript. The specification step for a call computes the argument list before it calls the function: "Let argList be ? ArgumentListEvaluation of argumentListNode."10 TypeScript compiles to JavaScript and keeps this rule.

C and C++. C has "a sequence point after the evaluation of all function arguments and of the function designator, and before the actual function call."11 C++ sequences "every argument expression and the postfix expression designating func" before "every expression or statement in the body of func".12 Neither language fixes the order of the arguments among themselves.

Bash. Before the shell runs a simple command, the words "are expanded", and the expansions run "from left to right".13 A command substitution in an argument runs to the end before the command starts.

PythonGitHub
def trace(label, value):
    print("evaluating", label)
    return value


def pick(flag, left, right):
    print("inside pick")
    return left if flag else right


print(pick(trace("flag", True), trace("left", 1), trace("right", 2)))
print(trace("x", False) and trace("y", True))
Output
evaluating flag
evaluating left
evaluating right
inside pick
1
evaluating x
False
  • Verdict: native. Python evaluates every argument, from left to right, before the body of the function runs. pick uses only left, but right is computed too.
  • and, or and the conditional expression a if c else b are the non-strict forms: trace("y", True) never runs, because False and ... is false.
  • Default parameter values are also computed eagerly, one time, when the def statement runs, and not at each call.
import logging

logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger("demo")


def build_report():
    print("building report")
    return "3 errors"


log.debug("report: %s", build_report())
if log.isEnabledFor(logging.DEBUG):
    log.debug("report: %s", build_report())
print("done")
Output
building report
done

The first call builds the report even though the debug level is off, because the argument runs before debug checks the level. The guarded call skips the work.

#include <functional>
#include <iostream>
#include <string>

int trace(const std::string& label, int value) {
    std::cout << "evaluating " << label << '\n';
    return value;
}

int twice(int n) {
    std::cout << "inside twice\n";
    return 2 * n;
}

int choose(bool flag, const std::function<int()>& left, const std::function<int()>& right) {
    return flag ? left() : right();
}

int main() {
    std::cout << twice(trace("n", 21)) << '\n';
    std::cout << choose(false, [] { return trace("left", 1); }, [] { return trace("right", 2); }) << '\n';
}
Output
evaluating n
inside twice
42
evaluating right
2
  • Verdict: native. Every argument expression is sequenced before the body of the function. The arguments are indeterminately sequenced among themselves, so the compiler chooses their order.
  • A lambda with no parameters is a thunk. choose calls only the lambda that it needs, so left never runs.
JavaGitHub
public class Main {
    static <T> T trace(String label, T value) {
        System.out.println("evaluating " + label);
        return value;
    }

    static int pick(boolean flag, int left, int right) {
        System.out.println("inside pick");
        return flag ? left : right;
    }

    public static void main(String[] args) {
        System.out.println(pick(trace("flag", true), trace("left", 1), trace("right", 2)));
        System.out.println(trace("x", false) && trace("y", true));
    }
}
Output
evaluating flag
evaluating left
evaluating right
inside pick
1
evaluating x
false
  • Verdict: native. The Java Language Specification fixes the order: each argument is fully evaluated before the arguments to its right, and all of them before the method body.
  • &&, || and ?: are the non-strict operators. A Supplier<T> parameter gives a non-strict argument: the method calls get() only if it needs the value.
#include <stdbool.h>
#include <stdio.h>

static int trace(const char *label, int value) {
    printf("evaluating %s\n", label);
    return value;
}

static int twice(int n) {
    puts("inside twice");
    return 2 * n;
}

int main(void) {
    printf("%d\n", twice(trace("n", 21)));
    bool result = trace("x", 0) && trace("y", 1);
    printf("%d\n", result);
    return 0;
}
Output
evaluating n
inside twice
42
evaluating x
0
  • Verdict: native. There is a sequence point after the evaluation of all the arguments and before the call, so each argument is a value when the body starts.
  • The order of the arguments among themselves is unspecified. A call such as f(trace("a", 1), trace("b", 2)) can print b before a, so this example traces only one argument per call.
  • &&, || and ?: are the non-strict operators of C. A macro can also delay an expression, because it pastes the text in place of the call.
static T Trace<T>(string label, T value)
{
    Console.WriteLine($"evaluating {label}");
    return value;
}

static int Pick(bool flag, int left, int right)
{
    Console.WriteLine("inside pick");
    return flag ? left : right;
}

static int PickLazy(bool flag, Func<int> left, Func<int> right) => flag ? left() : right();

Console.WriteLine(Pick(Trace("flag", true), Trace("left", 1), Trace("right", 2)));
Console.WriteLine(PickLazy(true, () => Trace("left", 1), () => Trace("right", 2)));
Output
evaluating flag
evaluating left
evaluating right
inside pick
1
evaluating left
1
  • Verdict: native. The C# specification states that the expressions of an argument list are always evaluated in textual order, before the function member runs.
  • A Func<T> parameter is a thunk. PickLazy calls only the delegate that it needs.
JavaScriptGitHub
function trace(label, value) {
  console.log("evaluating", label);
  return value;
}

function pick(flag, left, right) {
  console.log("inside pick");
  return flag ? left : right;
}

console.log(pick(trace("flag", true), trace("left", 1), trace("right", 2)));
console.log(trace("x", false) && trace("y", true));
Output
evaluating flag
evaluating left
evaluating right
inside pick
1
evaluating x
false
  • Verdict: native. A call evaluates its argument list from left to right and then calls the function. The arguments are values when the body starts.
  • &&, ||, ??, ?. and ?: evaluate an operand only when the result needs it.
TypeScriptGitHub
function trace<T>(label: string, value: T): T {
  console.log("evaluating", label);
  return value;
}

function pick(flag: boolean, left: () => number, right: () => number): number {
  console.log("inside pick");
  return flag ? left() : right();
}

console.log(pick(trace("flag", true), () => trace("left", 1), () => trace("right", 2)));
Output
evaluating flag
inside pick
evaluating left
1
  • Verdict: native. TypeScript has the evaluation rules of JavaScript: arguments are evaluated from left to right before the call.
  • The type () => number marks a parameter as a thunk. The caller passes a function, and the body decides if it calls it. Here only left runs, after inside pick.
package main

import "fmt"

func trace[T any](label string, value T) T {
	fmt.Println("evaluating", label)
	return value
}

func pick(flag bool, left, right int) int {
	fmt.Println("inside pick")
	if flag {
		return left
	}
	return right
}

func main() {
	fmt.Println(pick(trace("flag", true), trace("left", 1), trace("right", 2)))
	fmt.Println(trace("x", false) && trace("y", true))
	defer fmt.Println("deferred value:", trace("deferred", 42))
	fmt.Println("end of main")
}
Output
evaluating flag
evaluating left
evaluating right
inside pick
1
evaluating x
false
evaluating deferred
end of main
deferred value: 42
  • Verdict: native. Arguments are evaluated before the call, and function calls inside an expression run in lexical left-to-right order.
  • A defer statement evaluates its arguments at once, when the statement runs, but delays the call until the function returns. The trace shows evaluating deferred before end of main.
RustGitHub
fn trace<T>(label: &str, value: T) -> T {
    println!("evaluating {label}");
    value
}

fn pick(flag: bool, left: i32, right: i32) -> i32 {
    println!("inside pick");
    if flag { left } else { right }
}

fn main() {
    println!("{}", pick(trace("flag", true), trace("left", 1), trace("right", 2)));
    println!("{}", trace("x", false) && trace("y", true));
    let fallback: Option<i32> = None;
    println!("{}", fallback.unwrap_or_else(|| trace("closure", 7)));
}
Output
evaluating flag
evaluating left
evaluating right
inside pick
1
evaluating x
false
evaluating closure
7
  • Verdict: native. The Rust Reference states that the operands of a call are evaluated before the call, left to right as written.
  • The standard library pairs eager and lazy forms: unwrap_or(x) takes a value that is always computed, and unwrap_or_else(|| ...) takes a closure that runs only when needed.
BashGitHub
show() {
  echo "inside show: n=$n, arguments: $*"
}

n=0
show "$((n += 1))" "$((n += 10))"
false && echo "never printed"
echo "status after the && list: $?"
Output
inside show: n=11, arguments: 1 11
status after the && list: 1
  • Verdict: native. Before the shell runs a simple command, it expands the words from left to right. Both arithmetic expansions change n before show starts, so show sees n=11.
  • && and || run the right command only when the status of the left command requires it. false && echo never runs echo.

Call by value and call by reference. These are two ways to pass an argument in a strict language. Call by value copies the value, and call by reference passes the location of a variable. In both, the argument is ready before the body runs. See parameter passing.

Call by name and call by need. Algol 60 offered call by name next to call by value. A parameter that is not in the value list "is replaced, throughout the procedure body, by the corresponding actual parameter".14 The argument runs each time the body uses the parameter, and not before the call. Call by need is call by name with a stored result. Both are non-strict.

Thunks in a strict language. A strict language can simulate a non-strict argument: the caller wraps the expression in a function with no parameters, a thunk, and the body calls it only if it needs the value. A Python lambda: x / y, a Java Supplier and a Kotlin () -> T are thunks of this kind.

Lazy values in a strict language. Most strict languages offer lazy sequences and lazy initialization as library types. See lazy evaluation and lazy sequence and stream.

Strictness analysis. A compiler for a lazy language looks for functions that always use an argument. For such a function, strict evaluation of that argument gives the same result and costs less, so the compiler uses it.

Pitfalls

A user-defined conditional evaluates both branches. A function cannot replace if in a strict language. Both branch arguments run before the body can choose one:

This code runs but gives a wrong answer on purpose.

def choose(test, when_true, when_false):
    return when_true if test else when_false


count = 0
try:
    print(choose(count != 0, 100 / count, 0))
except ZeroDivisionError as error:
    print("error:", type(error).__name__)
Output
error: ZeroDivisionError

The guard count != 0 is false, but 100 / count runs first and fails. Pass thunks and call only the chosen one:

def choose(test, when_true, when_false):
    return when_true() if test else when_false()


count = 0
print(choose(count != 0, lambda: 100 / count, lambda: 0))
Output
0

Costly default work. A logging call such as log.debug(build_report()) builds the report even when the debug level is off, because the argument runs before the logger checks the level. Pass a thunk, or check the level first.

Side effects in arguments. A call such as f(next(it), next(it)) depends on the order of argument evaluation. It is defined in Python, Java and C#. In C and C++ the order is not specified, and cppreference lists f(++i, ++i) as undefined behavior in C.11 Put each effect in its own statement.

Infinite or failing arguments. In a strict language, an argument that never ends stops the whole call, even if the function would ignore it. Code that builds an infinite structure must make it lazy on purpose, for example with a generator.

Cost

Strict evaluation is cheap and predictable. The machine computes each argument once, on the call stack or in registers, and passes a value. There is no heap object for a suspended expression and no check of a ready flag on each use. Memory use follows the structure of the code, which makes it easy to reason about. SICP gives "the additional efficiency obtained from avoiding multiple evaluations of expressions" as one reason why Lisp uses applicative order.1

The cost is wasted work. A strict call computes arguments that the body does not use, and a strict pipeline builds each full intermediate collection before the next stage starts. A strict program cannot describe an infinite structure directly.

History

The Algol 60 report came from a conference in Paris in January 1960, and the revised report states the two modes of a procedure parameter in its section 4.7.3: value assignment "(call by value)" and name replacement "(call by name)".14 Call by value is strict, and call by name is not. Lisp used applicative order for its interpreter, and SICP still explains this choice with the efficiency of evaluating each argument once.1 Most later languages, from C to Java, Python and Rust, use strict evaluation for function arguments. Research languages such as SASL, Miranda and Haskell took the other road and made non-strict evaluation the default, and Haskell offers strict application as the operator $!.4

References

  1. Structure and Interpretation of Computer Programs, H. Abelson and G. J. Sussman, second edition, MIT Press, 1.1.5 The Substitution Model for Procedure Application, Applicative order versus normal order
  2. Evaluation strategy, Wikipedia, Strict evaluation; Non-strict evaluation
  3. Haskell 2010 Language Report, Expressions, chapter 3 introduction, Errors
  4. Haskell 2010 Language Report, Predefined Types and Classes, 6.2 Strict Evaluation
  5. Expressions, The Python Language Reference, Python 3.14, 6.3.4 Calls
  6. Chapter 15. Expressions, The Java Language Specification, Java SE 25 Edition, 15.7.4 Argument Lists are Evaluated Left-to-Right
  7. The Go Programming Language Specification, Calls; Order of evaluation
  8. Expressions, The Rust Reference, Evaluation order of operands
  9. Expressions, C# language specification, 12.6.2.3 Run-time evaluation of argument lists
  10. ECMAScript Language Specification, ECMAScript Language Expressions, 13.3.6.2 EvaluateCall
  11. Order of evaluation (C), cppreference.com, Rules, 1
  12. Order of evaluation (C++), cppreference.com, Rules, 3 and 13
  13. Bash Reference Manual, 3.7.1 Simple Command Expansion
  14. Revised Report on the Algorithmic Language Algol 60, P. Naur, editor, 4.7.3 Semantics (procedure statements); introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/2JK5K7/text.yaml