Why can't I reassign variables in a pure function?

← Purity Contracts · Ref: Q790

In EK9, pure functions cannot reassign variables using ':='. This ensures pure functions have no side effects — they compute a result from their inputs without modifying state.

WHAT IS ALLOWED IN PURE

- Declaration with initialisation: 'result <- computation()'
- Guarded assignment: 'value :=? fallback' (only assigns if unset)
- Return variable initialisation: '<- rtn as Type: expression'

WHAT IS NOT ALLOWED IN PURE

- Reassignment: 'existing := newValue' (E08100)
- Mutation operators: '+=', '-=', ':=:', '++', '--' (E08120)
- Calling non-pure methods (E08130)

THIS EXAMPLE

The add() function is pure. It declares result with '<-' and returns it. No reassignment needed.

WHY PURITY MATTERS

1. Pure functions are thread-safe — no shared mutable state
2. Results are cacheable — same inputs always produce same output
3. Easier to test — no setup or teardown of state
4. Compiler can optimise — knows no side effects occur

See Q43 for pure function basics. See Q560 for purity contracts.

Example

defines module qa.puritycontracts.noreassignment

  defines function

    add() as pure
      ->
        left as Integer
        right as Integer
      <- rtn as Integer?

      total <- left + right
      rtn: total

  defines program

    ShowAdd()
      stdout <- Stdout()
      result <- add(10, 20)
      stdout.println($result)

Common mistakes

E08100 — Reassigning 'total' with ':=' is not allowed in a pure function. Use declaration with initialisation '<-' instead. Pure functions cannot modify variables after declaration. See ek9 -h E08100 for details.

Incorrect:

      total <- 0
      total := left + right

Correct:

      total <- left + right

E08120 — Using the mutation operator '+=' in a pure function is not allowed. Mutation operators modify state in place — pure functions must not mutate. Use '<- left + right' to compute the result in a single declaration. See ek9 -h E08120 for details.

Incorrect:

      total <- left
      total += right

Correct:

      total <- left + right
Other ways to ask this
  • What triggers E08100 no pure reassignment?
  • What is allowed in a pure context in EK9?
  • How do I write pure functions without reassignment?

Coming from another language?

Java: no purity enforcement, rely on convention. Python: no purity concept. Rust: mut keyword controls mutability but no function-level purity. Kotlin: val prevents reassignment but no pure functions. Go: no purity concept. Haskell: all functions pure by default. EK9: explicit 'as pure' keyword with compiler enforcement.

Keywords: function, side effect, reassignment, thread safe, pure, E08100, immutable