- Concepts of Programming Languages

Strict and Nonstrict Evaluation

Instructor:

Learning Objectives

How much of an expression should be evaluated when computing a result?

  • Perform expression evaluation
  • Perform function calls and function argument evaluation

Strict and Nonstrict Operators

  • A strict construct evaluates all of its operands before it runs

Strict constructs

  • Arithmetic operators: +, -, ...
  • Comparison operators: <, <=, ...
  • Bitwise operators: |, &, ...
  • Function calls: f(x,y)

Non-strict constructs

  • e1 && e2: strict in e1, but not e2
  • e1 || e2: strict in e1, but not e2
  • if e1 then e2 else e3: strict in e1, but not e2 or e3

Conditionals in C

  • Conditional statement: executes return 1 or return n*..., never both
  1. int fact (int n) {
  2. if (n <= 1) {
  3. return 1;
  4. } else {
  5. return n * fact (n - 1);
  6. }
  7. }
  • Conditional expression: must be non-strict, otherwise non-terminating recursion
  1. int fact (int n) {
  2. return (n <= 1) ? 1 : n * fact (n - 1);
  3. }

Conditionals in Formal Semantics

Rules for Conditional: what is the difference?

  • If-True:
  • If-False:
  • If:

What Happens?

  • Function calls are strict
  1. def f(b: Boolean, t: Unit, f: Unit) : Unit =
  2. if b then t else f
  • Invoke f

    1. def g(x: Int) =
    2. print(x)
    3. f(x % 2 == 0,
    4. println(": even"),
    5. println(": odd"))
    6. end g
    7. g(3)
  • Both "even" and "odd" are printed

What Happens?

  • Thunks: pass-by-name for explicit nonstrict evaluation of function arguments
  1. def f(b: Boolean, t: => Unit, f: => Unit) : Unit =
  2. if b then t else f
  • Invoke f

    1. def g(x: Int) =
    2. print(x)
    3. f(x % 2 == 0,
    4. println(": even"),
    5. println(": odd"))
    6. end g
    7. g(3)
  • prints only "odd"

Example: Control Constructs for Kleene K3

  • Kleene K3: three-valued logic (true, false, indeterminate)
  • Implement if conditional with 3 branches

Summary

Strict Evaluation

  • Evaluates all operands to determine value of an expression
    • Arithmetic operators etc.
    • Function arguments

Nonstrict Evaluation

  • Evaluates only necessary operands to determine value
    • Conditional expression
    • Shortcut evaluation of boolean expressions
  • Thunks: request explicit nonstrict evaluation of function arguments

# <span class="fa-stack"><i class="fa-solid fa-circle fa-stack-2x"></i><i class="fa-solid fa-dumbbell fa-stack-1x fa-inverse"></i></span> Conditional Expression Conditional expression `if e1 then e2 else e3` - Evaluate `e1`; if `true` then evaluate `e2`, else evaluate `e3` ```scala for i <- 0 to 10 do print(i) if i % 2 == 0 then println(": even") else println(": odd") end for ``` </div> ---