Pure Functions

Definition and Characteristics of Pure Functions

A pure function is a fundamental concept in functional programming meaning that:

  1. The function's result depends solely on its input parameters (determinism)
  2. The function's execution does not cause side effects

A side effect is any action performed by a function beyond simply returning a computed value, including:

Formal Specification of Pure Functions

From a mathematical perspective, a pure function f: A => B represents:

This definition makes pure functions analogous to mathematical functions, where f(x) = x² will always give the same result for the same x.

Referential Transparency: In-Depth Analysis

Reference transparency is a key property of functional programs, meaning that:

Advantages of referential transparency:

  1. Correctness verification: Ability to formally prove code correctness
  2. Simplified refactoring: Safe replacement of expressions with equivalent ones
  3. Optimizations:
    • Memoization (caching results)
    • Lazy evaluation
    • Parallel execution
  4. Predictability: The program's behavior becomes fully predictable

In imperative languages, most functions are not referentially transparent due to state dependencies.

Exercise 1.2.1: Identifying Pure Functions

Repository with exercises and instructions

Analyze three implementations of a division function and choose the pure version:

def pureFunction(a: Int, b: Int): Int =
  def innerFirst(a: Int, b: Int): Int = a / b

  def innerSecond(a: Int, b: Int): Int =
    if (b == 0) Int.MaxValue else a / b

  def innerThird(a: Int, b: Int): Int =
    require(b != 0, "Division by zero!")
    a / b

  // innerFirst(a, b)
  // innerSecond(a, b)
  // innerThird(a, b)
  ???

🔍 Show Solution

Analysis criteria:

  1. innerFirst:
    • Not pure: at b=0 it throws an exception (side effect)
    • Violates referential transparency (different behavior for b=0)
  2. innerSecond:
    • Pure: always returns a value
    • Deterministic: same inputs → same outputs
    • No side effects
  3. innerThird:
    • Not pure: require throws an IllegalArgumentException
    • Alters execution flow (side effect)

Conclusion: Only innerSecond satisfies all purity conditions:

  • Complete handling of all input cases
  • No exceptions
  • Independence from external state

Links: