Programming Search⌘K

Conceptcore

Expression problem

Also called the expression problem, extensibility problem, two-dimensional extensibility.

The expression problem asks how to add both new cases and new operations to a data type without changing existing code and with static checks. Classes make one easy, pattern matching the other.

Applies to
core-languages

Idea

The expression problem asks how to extend a data type in two directions at once: with new cases, and with new operations over all the cases, without changing or recompiling the existing code and without giving up static type safety. Philip Wadler named it in 1998: "The goal is to define a datatype by cases, where one can add new cases to the datatype and new functions over the datatype, without recompiling existing code, and while retaining static type safety (e.g., no casts)."1 Object-oriented code makes new cases easy and new operations hard. Functional code with pattern matching makes new operations easy and new cases hard. Every language design picks a side, or adds a mechanism to get both.

from dataclasses import dataclass
from functools import singledispatch


@dataclass
class Num:  # the first two cases of the data type
    value: int


@dataclass
class Add:
    left: object
    right: object


@singledispatch  # an operation: one generic function, one method for each case
def evaluate(e):
    raise TypeError(f"evaluate has no case for {type(e).__name__}")


@evaluate.register
def _(e: Num):
    return e.value


@evaluate.register
def _(e: Add):
    return evaluate(e.left) + evaluate(e.right)


@singledispatch
def show(e):
    raise TypeError(f"show has no case for {type(e).__name__}")


@show.register
def _(e: Num):
    return str(e.value)


@show.register
def _(e: Add):
    return f"({show(e.left)} + {show(e.right)})"


print(show(Add(Num(1), Num(2))), "=", evaluate(Add(Num(1), Num(2))))


# Later, without a change to the code above: a new case ...
@dataclass
class Neg:
    inner: object


evaluate.register(Neg, lambda e: -evaluate(e.inner))
show.register(Neg, lambda e: f"-{show(e.inner)}")


# ... and a new operation.
@singledispatch
def depth(e):
    raise TypeError(f"depth has no case for {type(e).__name__}")


depth.register(Num, lambda e: 1)
depth.register(Add, lambda e: 1 + max(depth(e.left), depth(e.right)))
depth.register(Neg, lambda e: 1 + depth(e.inner))

e = Add(Num(1), Neg(Add(Num(2), Num(3))))
print(show(e), "=", evaluate(e), "depth", depth(e))


@dataclass
class Mul:  # a case that nobody taught evaluate
    left: object
    right: object


try:
    evaluate(Mul(Num(2), Num(3)))
except TypeError as err:
    print(err)
Output
(1 + 2) = 3
(1 + -(2 + 3)) = -4 depth 4
evaluate has no case for Mul

The data type is a small language of arithmetic expressions. Each operation is a generic function from functools.singledispatch, which chooses a method by the type of its argument, so the cases and the operations are separate and either side can grow. The code after the first print adds the case Neg and the operation depth without a change to the code above it. The cost shows at the end: Python itself checks nothing until the program runs, so a case that an operation does not know about fails only when the operation reaches it. Wadler's problem asks for the same freedom with the check done by the compiler.

How it works

A table of cases and operations. Write the cases of the data type as the rows of a table and the operations as its columns. Each cell is the code for one operation on one case. Wadler described the two usual layouts: "In a functional language, the rows are fixed (cases in a datatype declaration) but it is easy to add new columns (functions). In an object-oriented language, the columns are fixed (methods in a class declaration) but it is easy to add new rows (subclasses). We want to make it easy to add either rows or columns."1 A program keeps the table in one of two orientations, and the orientation decides which kind of change touches existing code.

The object-oriented side. Each case is a class, and each operation is a method that every class implements. A new case is a new class, written in one place, with no change to the others. A new operation is a new method in the base type, which every existing class must implement, so the change spreads over every case, often across modules that belong to other people. See dynamic dispatch and class inheritance.

The functional side. The cases are the variants of a sum type, and each operation is a function that uses pattern matching over the variants. A new operation is one new function. A new case is a new variant, and every function that matches over the type must add a branch for it. A compiler that checks exhaustiveness, as in Rust, Java with sealed types, Haskell or OCaml, lists every function to change, but the change still reaches code that was finished.

The visitor pattern moves the problem. In an object-oriented language, the visitor pattern puts each operation in a class of its own, with one method for each case. This turns the class hierarchy into the functional layout: a new operation is a new visitor, and a new case adds a method to the visitor interface and so to every visitor. The pattern changes which direction is easy but does not make both easy.

Static type safety is the hard part. A dynamic language can extend both sides with open classes, registries or generic functions, as the Python example does, and report a missing cell at run time. The problem asks for more: the compiler must reject a program in which some operation has no code for some case, and the extension must happen in new modules that the compiler checks separately. Wadler treated this as a test of a language: "Whether a language can solve the Expression Problem is a salient indicator of its capacity for expression."1

Mechanisms that solve it. Several language features give both directions with static checks. Type classes and traits keep each operation as its own interface, with an implementation for each case type, written anywhere: a new operation is a new trait, and a new case is a new type with impls of the existing traits. Rust limits where impls may appear, to keep one impl for each pair of trait and type: "The orphan rule states that a trait implementation is only allowed if either the trait or at least one of the types in the implementation is defined in the current crate. It prevents conflicting trait implementations across different crates and is key to ensuring coherence."2 Clojure protocols have the same goal, to "Avoid the 'expression problem' by allowing independent extension of the set of types, protocols, and implementations of protocols on types, by different parties".3 Generic programming with type parameters, as in Wadler's own solution in Generic Java, and object algebras give further solutions in languages with classes.

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaIdiom
CIdiom
C#Idiom
JavaScriptIdiom
TypeScriptIdiomA discriminated union with a switch and a never check gives exhaustive operations, and declaration merging can add methods to existing classes.
GoIdiom
RustIdiom
KotlinIdiomSealed classes with an exhaustive when keep cases closed, and extension functions add operations to existing types with static dispatch; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyTables and functions extend independently, but the language has no user-defined sum types or dispatch over cases.
BashDoes not applyBash has no user-defined data types to extend.
PowerShellIdiomUpdate-TypeData adds script methods and properties to existing .NET types at run time; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML has no data types or operations to extend.
CSSDoes not applyCSS has no data types or operations to extend.
Regular expressionsDoes not applyA pattern has no data types or operations to extend.
Language Verdict Mechanism
Python idiom classes; functools.singledispatch; checks at run time
JavaScript idiom open prototypes; methods keyed by symbols
TypeScript idiom discriminated unions with exhaustive switch
Java idiom classes; visitors; sealed interfaces with switch
Kotlin idiom sealed classes with when; extension functions
C# idiom classes; extension methods with switch expressions
Go idiom implicit interfaces; type switches
Rust idiom one trait for each operation; enums with match
C idiom tagged unions; tables of function pointers
C++ idiom virtual functions; std::variant with std::visit
Bash n/a no user-defined data types
PowerShell idiom Update-TypeData adds members to existing types
SQL n/a no user-defined sum types or dispatch
Regex n/a no data types
HTML n/a no data types
CSS n/a no data types

No core language of this site solves the expression problem with one feature, and each gives a set of partial solutions. Every example file builds the same small language of numbers, addition and negation, adds a case and an operation, and shows where the language makes one of the two changes reach existing code. The failing and wrong blocks show the side that is closed in each language: a switch that misses a case, a sealed type, a method that cannot go on a foreign type, or a table with a hole.

The languages fall into three groups. Python and JavaScript extend both sides with no static check, by registries and open prototypes. Java, C#, C++, Kotlin and TypeScript give the object-oriented layout through classes and the functional layout through sealed types or variants, and a program picks one layout for each data type. Rust, with traits, comes closest to a full solution among the core languages. Go lets a new case come from any package, because a type satisfies an interface without a declaration, but its type switches have no exhaustiveness check. Outside the core set, Haskell type classes, Clojure protocols and the multimethods of Common Lisp and Julia give this kind of extension directly.

PythonGitHub
from abc import ABC, abstractmethod


class Expr(ABC):  # object-oriented: each operation is a method
    @abstractmethod
    def evaluate(self): ...

    @abstractmethod
    def show(self): ...


class Num(Expr):
    def __init__(self, value):
        self.value = value

    def evaluate(self):
        return self.value

    def show(self):
        return str(self.value)


class Add(Expr):
    def __init__(self, left, right):
        self.left, self.right = left, right

    def evaluate(self):
        return self.left.evaluate() + self.right.evaluate()

    def show(self):
        return f"({self.left.show()} + {self.right.show()})"


class Neg(Expr):  # a new case: one new class, no other change
    def __init__(self, inner):
        self.inner = inner

    def evaluate(self):
        return -self.inner.evaluate()

    def show(self):
        return f"-{self.inner.show()}"


e = Add(Num(1), Neg(Num(5)))
print(e.show(), "=", e.evaluate())


class Mul(Expr):  # a case that forgets one operation
    def __init__(self, left, right):
        self.left, self.right = left, right

    def evaluate(self):
        return self.left.evaluate() * self.right.evaluate()


try:
    Mul(Num(2), Num(3))
except TypeError as err:
    print(err)
Output
(1 + -5) = -4
Can't instantiate abstract class Mul without an implementation for abstract method 'show'

This code runs but gives a wrong answer on purpose.

from dataclasses import dataclass


@dataclass
class Num:
    value: int


@dataclass
class Add:
    left: object
    right: object


@dataclass
class Neg:  # a case added after evaluate was written
    inner: object


def evaluate(e):  # functional: each operation is a function over all cases
    match e:
        case Num(v):
            return v
        case Add(l, r):
            return evaluate(l) + evaluate(r)
    # no case for Neg: the function returns None


print(evaluate(Add(Num(1), Num(2))))
print(evaluate(Neg(Num(5))))
Output
3
None
  • Verdict: idiom. Python has no construct for the expression problem, but its dynamic types make both directions possible. A class hierarchy makes cases easy to add, and an abstract method makes a new class fail when it is created if it omits an operation, as Mul shows. functools.singledispatch gives an open generic function: any module can register a new type for an existing operation, or create a new operation for existing types. All the checks happen at run time.
  • The wrong block writes the operation as a function with match. A case that the function does not handle falls out of the match and returns None, and the error appears later, far from its cause. End such a function with case _: raise TypeError(...), or use typing.assert_never so that a type checker reports the missing case.
#include <iostream>
#include <memory>
#include <string>
#include <variant>

// Closed cases, open operations: a std::variant and std::visit.
struct Num;
struct Add;
struct Neg;
using Expr = std::variant<Num, Add, Neg>;

struct Num { int value; };
struct Add { std::shared_ptr<Expr> left, right; };
struct Neg { std::shared_ptr<Expr> inner; };

template <class... Fs>
struct overloaded : Fs... { using Fs::operator()...; };

int eval(const Expr& e)
{
    return std::visit(overloaded{
        [](const Num& n) { return n.value; },
        [](const Add& a) { return eval(*a.left) + eval(*a.right); },
        [](const Neg& g) { return -eval(*g.inner); },
    }, e);
}

// A new operation: one new function. Every arm must be present, or the code does not compile.
std::string show(const Expr& e)
{
    return std::visit(overloaded{
        [](const Num& n) { return std::to_string(n.value); },
        [](const Add& a) { return "(" + show(*a.left) + " + " + show(*a.right) + ")"; },
        [](const Neg& g) { return "-" + show(*g.inner); },
    }, e);
}

std::shared_ptr<Expr> num(int v) { return std::make_shared<Expr>(Num{v}); }
std::shared_ptr<Expr> add(std::shared_ptr<Expr> l, std::shared_ptr<Expr> r)
{
    return std::make_shared<Expr>(Add{l, r});
}
std::shared_ptr<Expr> neg(std::shared_ptr<Expr> x) { return std::make_shared<Expr>(Neg{x}); }

int main()
{
    auto e = add(num(1), neg(add(num(2), num(3))));
    std::cout << show(*e) << " = " << eval(*e) << '\n';
}
Output
(1 + -(2 + 3)) = -4

This code does not compile, on purpose.

#include <iostream>
#include <variant>

struct Num { int value; };
struct Neg { int inner; };  // a new case
using Expr = std::variant<Num, Neg>;

template <class... Fs>
struct overloaded : Fs... { using Fs::operator()...; };

int eval(const Expr& e)
{
    return std::visit(overloaded{
        [](const Num& n) { return n.value; },
        // no arm for Neg
    }, e);
}

int main()
{
    std::cout << eval(Neg{5}) << '\n';
}
  • Verdict: idiom. C++ has both forms in the standard language. A class hierarchy with virtual functions keeps the cases open and the operations closed. A std::variant with std::visit keeps the cases closed and the operations open: a new operation is one new function, and the overload set of lambdas, built by the overloaded helper, gives one arm per case. Templates can solve the problem fully, at the price of code that is hard to read.
  • The failing block adds Neg to the variant without an arm for it. std::visit requires a visitor that can take every alternative, so the compiler rejects the call, and every operation that misses the new case fails to compile.
JavaGitHub
// The visitor pattern: the cases are fixed, and each operation is a new class.
interface Expr {
    <R> R accept(Visitor<R> v);
}

interface Visitor<R> {
    R num(int value);
    R add(Expr left, Expr right);
}

record Num(int value) implements Expr {
    public <R> R accept(Visitor<R> v) { return v.num(value); }
}

record Add(Expr left, Expr right) implements Expr {
    public <R> R accept(Visitor<R> v) { return v.add(left, right); }
}

class Eval implements Visitor<Integer> {
    public Integer num(int value) { return value; }
    public Integer add(Expr l, Expr r) { return l.accept(this) + r.accept(this); }
}

// A new operation: one new class, no change to Expr, Num or Add.
class Show implements Visitor<String> {
    public String num(int value) { return Integer.toString(value); }
    public String add(Expr l, Expr r) {
        return "(" + l.accept(this) + " + " + r.accept(this) + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        Expr e = new Add(new Num(1), new Add(new Num(2), new Num(3)));
        String text = e.accept(new Show());
        int value = e.accept(new Eval());
        System.out.println(text + " = " + value);
    }
}
Output
(1 + (2 + 3)) = 6

This code does not compile, on purpose.

// A sealed interface lists every case; a switch over it must cover them all.
sealed interface Expr permits Num, Add, Neg {}

record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Neg(Expr inner) implements Expr {}  // a new case

public class Main {
    static int evaluate(Expr e) {
        return switch (e) {
            case Num n -> n.value();
            case Add a -> evaluate(a.left()) + evaluate(a.right());
            // no case for Neg
        };
    }

    public static void main(String[] args) {
        System.out.println(evaluate(new Add(new Num(1), new Neg(new Num(5)))));
    }
}
  • Verdict: idiom. Java gives both halves of the problem. With classes and methods, a new case is a new class. With the visitor pattern, a new operation is a new class that implements Visitor, but a new case must add a method to Visitor and to every class that implements it. With a sealed interface and records, a switch over the cases needs no visitor, and the compiler checks that the switch covers every permitted case.
  • The failing block adds Neg to the sealed interface without a branch for it. The compiler rejects the switch because it does not cover all possible input values, so the programmer finds every operation to update. The check works only inside the code that declares the sealed interface, and code outside it cannot add a case at all.
#include <stdio.h>

/* The cases form a tagged union; each operation is a table of functions, one per tag. */
enum tag { NUM, ADD, NEG, NTAGS };

struct expr {
    enum tag tag;
    int value;
    const struct expr *left, *right;
};

typedef int (*eval_fn)(const struct expr *);
static int eval(const struct expr *e);

static int eval_num(const struct expr *e) { return e->value; }
static int eval_add(const struct expr *e) { return eval(e->left) + eval(e->right); }
static int eval_neg(const struct expr *e) { return -eval(e->left); }

static const eval_fn eval_table[NTAGS] = {
    [NUM] = eval_num, [ADD] = eval_add, [NEG] = eval_neg,
};

static int eval(const struct expr *e) { return eval_table[e->tag](e); }

/* A new operation: a new table, filled for every tag. */
typedef void (*show_fn)(const struct expr *);
static void show(const struct expr *e);

static void show_num(const struct expr *e) { printf("%d", e->value); }
static void show_add(const struct expr *e)
{
    printf("(");
    show(e->left);
    printf(" + ");
    show(e->right);
    printf(")");
}
static void show_neg(const struct expr *e)
{
    printf("-");
    show(e->left);
}

static const show_fn show_table[NTAGS] = {
    [NUM] = show_num, [ADD] = show_add, [NEG] = show_neg,
};

static void show(const struct expr *e) { show_table[e->tag](e); }

int main(void)
{
    struct expr one = {.tag = NUM, .value = 1};
    struct expr two = {.tag = NUM, .value = 2};
    struct expr three = {.tag = NUM, .value = 3};
    struct expr sum = {.tag = ADD, .left = &two, .right = &three};
    struct expr neg = {.tag = NEG, .left = &sum};
    struct expr top = {.tag = ADD, .left = &one, .right = &neg};
    show(&top);
    printf(" = %d\n", eval(&top));
    return 0;
}
Output
(1 + -(2 + 3)) = -4

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>

enum tag { NUM, ADD, MUL, NTAGS }; /* MUL added after the tables were written */

struct expr {
    enum tag tag;
    int value;
    const struct expr *left, *right;
};

typedef int (*eval_fn)(const struct expr *);
static int eval(const struct expr *e);

static int eval_num(const struct expr *e) { return e->value; }
static int eval_add(const struct expr *e) { return eval(e->left) + eval(e->right); }

static const eval_fn eval_table[NTAGS] = {
    [NUM] = eval_num, [ADD] = eval_add, /* no entry for MUL: a null pointer */
};

static int eval(const struct expr *e) { return eval_table[e->tag](e); }

int main(void)
{
    struct expr two = {.tag = NUM, .value = 2}, three = {.tag = NUM, .value = 3};
    struct expr product = {.tag = MUL, .left = &two, .right = &three};
    printf("%d\n", eval(&product));
    return 0;
}
  • Verdict: idiom. C has no dispatch of its own, so a program builds it: a tag in each value names the case, and each operation is an array of function pointers indexed by the tag. A new operation is a new table. A new case is a new tag and an entry in every table, so the tables of all operations must change.
  • The failing block adds the tag MUL but no entry in the table for eval. The designated initializer leaves the entry as a null pointer, and the call through it crashes, which AddressSanitizer reports as a SEGV. A switch over the tag with -Wswitch enabled and no default lets the compiler warn about the missing case instead.
// Cases are records; operations are extension methods with a switch.
var e = new Add(new Num(1), new Neg(new Add(new Num(2), new Num(3))));
Console.WriteLine($"{e.Show()} = {e.Evaluate()}");

public abstract record Expr;
public record Num(int Value) : Expr;
public record Add(Expr Left, Expr Right) : Expr;
public record Neg(Expr Inner) : Expr;

public static class Eval
{
    public static int Evaluate(this Expr e) => e switch
    {
        Num n => n.Value,
        Add a => a.Left.Evaluate() + a.Right.Evaluate(),
        Neg g => -g.Inner.Evaluate(),
        _ => throw new ArgumentException($"no case for {e.GetType().Name}"),
    };
}

// A new operation in another class: the records do not change.
public static class Printing
{
    public static string Show(this Expr e) => e switch
    {
        Num n => n.Value.ToString(),
        Add a => $"({a.Left.Show()} + {a.Right.Show()})",
        Neg g => $"-{g.Inner.Show()}",
        _ => throw new ArgumentException($"no case for {e.GetType().Name}"),
    };
}
Output
(1 + -(2 + 3)) = -4

This code runs but gives a wrong answer on purpose.

Expr e = new Mul(new Num(2), new Num(3));
Console.WriteLine(e.Show());
Console.WriteLine(new Mul(new Num(2), new Num(3)).Show());

public abstract record Expr;
public record Num(int Value) : Expr;
public record Mul(Expr Left, Expr Right) : Expr;  // a case added later

public static class Printing
{
    public static string Show(this Expr e) => e switch
    {
        Num n => n.Value.ToString(),
        _ => $"<{e.GetType().Name}?>",
    };
}

// The new case adds its own overload instead of a switch arm.
public static class MulPrinting
{
    public static string Show(this Mul m) => $"({m.Left.Show()} * {m.Right.Show()})";
}
Output
<Mul?>
(2 * 3)
  • Verdict: idiom. Extension methods let a class in any assembly add an operation that reads as a method of the existing types, and a switch expression with type patterns selects the case. Records give short case types. The compiler warns when a switch expression on a type does not cover every value, and the discard arm _ turns a missing case into an exception at run time.
  • The wrong block adds a case with its own overload of the extension method. Extension methods bind at compile time by the static type of the receiver, so a call through a variable of type Expr picks Show(this Expr), and the overload for Mul runs only when the static type is Mul. A new case must add an arm to the switch, or the operation must be a virtual method of the case types.
JavaScriptGitHub
// Cases are classes; each operation is a method on the prototype.
class Num {
  constructor(value) { this.value = value; }
  evaluate() { return this.value; }
}

class Add {
  constructor(left, right) { this.left = left; this.right = right; }
  evaluate() { return this.left.evaluate() + this.right.evaluate(); }
}

// A new operation, added later from another module, without editing the classes.
const show = Symbol("show");
Num.prototype[show] = function () { return String(this.value); };
Add.prototype[show] = function () {
  return `(${this.left[show]()} + ${this.right[show]()})`;
};

// A new case that supplies both operations.
class Neg {
  constructor(inner) { this.inner = inner; }
  evaluate() { return -this.inner.evaluate(); }
  [show]() { return `-${this.inner[show]()}`; }
}

const e = new Add(new Num(1), new Neg(new Add(new Num(2), new Num(3))));
console.log(e[show](), "=", e.evaluate());

class Mul {  // a new case that does not know about show
  constructor(left, right) { this.left = left; this.right = right; }
  evaluate() { return this.left.evaluate() * this.right.evaluate(); }
}
try {
  new Add(new Num(1), new Mul(new Num(2), new Num(3)))[show]();
} catch (err) {
  console.log(err.constructor.name, err.message);
}
Output
(1 + -(2 + 3)) = -4
TypeError this.right[show] is not a function

This code runs but gives a wrong answer on purpose.

// Cases are plain objects with a tag; each operation is a switch over the tags.
function evaluate(e) {
  switch (e.kind) {
    case "num": return e.value;
    case "add": return evaluate(e.left) + evaluate(e.right);
  }
}

const num = (value) => ({ kind: "num", value });
const add = (left, right) => ({ kind: "add", left, right });
const neg = (inner) => ({ kind: "neg", inner });  // a case added later

console.log(evaluate(add(num(1), neg(num(5)))));
Output
NaN
  • Verdict: idiom. JavaScript objects are open: a module can add a method to the prototype of a class that another module defined, so new operations and new cases both need no edit to existing code. A symbol as the method key keeps the new operation from clashing with names that other code adds. A case that lacks the operation fails only when the operation reaches it, with a TypeError.
  • The wrong block uses objects with a kind tag and a switch in each operation. The new neg case has no branch, so evaluate returns undefined, and adding it to a number gives NaN with no error. Add a default branch that throws, or use TypeScript, which can check that a switch covers every member of a union.
package main

import "fmt"

// Cases are types; the interface fixes one operation, Eval.
type Expr interface{ Eval() int }

type Num struct{ V int }
type Add struct{ L, R Expr }

func (n Num) Eval() int { return n.V }
func (a Add) Eval() int { return a.L.Eval() + a.R.Eval() }

// A new case: a new type with an Eval method.
type Neg struct{ X Expr }

func (n Neg) Eval() int { return -n.X.Eval() }

// A new case can bring its own Show; Show asks for it first.
type Shower interface{ Show() string }

// A new operation: a function with a type switch over the cases.
func Show(e Expr) string {
	if s, ok := e.(Shower); ok {
		return s.Show()
	}
	switch e := e.(type) {
	case Num:
		return fmt.Sprint(e.V)
	case Add:
		return "(" + Show(e.L) + " + " + Show(e.R) + ")"
	case Neg:
		return "-" + Show(e.X)
	}
	return fmt.Sprintf("<%T?>", e)
}

// A case added after Show was written.
type Mul struct{ L, R Expr }

func (m Mul) Eval() int    { return m.L.Eval() * m.R.Eval() }
func (m Mul) Show() string { return "(" + Show(m.L) + " * " + Show(m.R) + ")" }

func main() {
	e := Add{Num{1}, Neg{Add{Num{2}, Num{3}}}}
	fmt.Println(Show(e), "=", e.Eval())
	m := Add{Num{1}, Mul{Num{2}, Num{3}}}
	fmt.Println(Show(m), "=", m.Eval())
}
Output
(1 + -(2 + 3)) = -4
(1 + (2 * 3)) = 7

This code does not compile, on purpose.

package main

import (
	"fmt"
	"time"
)

// Add an operation to a type from another package.
func (d time.Duration) Minutes2() float64 { return d.Minutes() }

func main() {
	fmt.Println(time.Duration(90 * time.Second).Minutes2())
}
  • Verdict: idiom. An interface fixes a set of methods, and any type in any package that has them is a case, with no declaration. A new operation is a function with a type switch over the known cases. A new case can bring its own version of the operation by implementing an optional interface, here Shower, which the function checks first. The type switch has no exhaustiveness check, so a forgotten case reaches the fallback at run time.
  • The failing block defines a method on time.Duration. Go allows methods only on types that the same package defines, so code cannot add an operation as a method of a type from another package. Wrap the type in a new named type, or write a function.
RustGitHub
// Each case is a type, and each operation is a trait.
struct Num(i64);
struct Add<L, R>(L, R);

trait Eval {
    fn eval(&self) -> i64;
}

impl Eval for Num {
    fn eval(&self) -> i64 { self.0 }
}

impl<L: Eval, R: Eval> Eval for Add<L, R> {
    fn eval(&self) -> i64 { self.0.eval() + self.1.eval() }
}

// A new operation: a new trait with an impl for each existing case.
trait Show {
    fn show(&self) -> String;
}

impl Show for Num {
    fn show(&self) -> String { self.0.to_string() }
}

impl<L: Show, R: Show> Show for Add<L, R> {
    fn show(&self) -> String { format!("({} + {})", self.0.show(), self.1.show()) }
}

// A new case: a new type with an impl of each operation.
struct Neg<E>(E);

impl<E: Eval> Eval for Neg<E> {
    fn eval(&self) -> i64 { -self.0.eval() }
}

impl<E: Show> Show for Neg<E> {
    fn show(&self) -> String { format!("-{}", self.0.show()) }
}

// An operation can also cover a type from the standard library.
impl Eval for i64 {
    fn eval(&self) -> i64 { *self }
}

impl Show for i64 {
    fn show(&self) -> String { self.to_string() }
}

fn report<E: Eval + Show>(e: &E) {
    println!("{} = {}", e.show(), e.eval());
}

fn main() {
    report(&Add(Num(1), Neg(Add(Num(2), Num(3)))));
    report(&Add(10_i64, Neg(4_i64)));
}
Output
(1 + -(2 + 3)) = -4
(10 + -4) = 6

This code does not compile, on purpose. The error is E0004.

enum Expr {
    Num(i64),
    Add(Box<Expr>, Box<Expr>),
    Neg(Box<Expr>), // a new variant
}

fn eval(e: &Expr) -> i64 {
    match e {
        Expr::Num(n) => *n,
        Expr::Add(l, r) => eval(l) + eval(r),
    }
}

fn main() {
    let e = Expr::Add(Box::new(Expr::Num(1)), Box::new(Expr::Neg(Box::new(Expr::Num(5)))));
    println!("{}", eval(&e));
}

This code does not compile, on purpose. The error is E0117.

use std::fmt;

// Display and Vec both come from the standard library.
impl fmt::Display for Vec<i64> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} items", self.len())
    }
}

fn main() {
    println!("{}", vec![1_i64, 2, 3]);
}
  • Verdict: idiom. With one generic struct for each case and one trait for each operation, both kinds of extension need only new code: a new operation is a new trait with an impl for each case, and a new case is a new struct with an impl of each trait. A trait can also cover a type from another crate, as Eval for i64 shows, so integers act as numbers in an expression. The compiler checks every combination statically, because the type of an expression records its whole shape.
  • With an enum the cases are closed. The first failing block adds the variant Neg, and the compiler rejects every match that does not cover it, with error E0004. The second failing block shows the limit on the open side: the orphan rule allows an impl only if the trait or the type comes from the current crate, and Display and Vec both come from the standard library, so the compiler reports E0117. A local wrapper type, the newtype pattern, gets around it.
  • The visitor pattern. Puts each operation in a class with one method for each case, which makes new operations easy in an object-oriented language and new cases hard.
  • Sealed types and exhaustive matching. Close the set of cases on purpose, so that the compiler can check every operation. This is the functional side of the problem, chosen for data whose cases are known.
  • Type classes and traits. Separate each operation from the data, with implementations written for each type. Haskell type classes, Rust traits and Swift protocols with extensions work this way. See interfaces.
  • Multimethods and open generic functions. Choose code by the run-time types of one or more arguments, and let any module add methods. CLOS, Julia and Clojure have them, and Python's singledispatch gives a form with one argument.
  • Clojure protocols. Named sets of functions that any type, including a type from Java, can implement after the fact.
  • Object algebras. Bruno Oliveira and William Cook showed in 2012 a solution in Java and C# that uses only generic interfaces, with one factory interface for the cases and one implementation for each operation.
  • Tagless final. Represents a term of a language as a function that is generic over its interpretation, so new interpreters and, with type classes, new constructs can be added separately.
  • Open classes and monkey patching. Ruby, JavaScript and Objective-C categories let any module add methods to existing classes, which solves both sides at run time with the risk of name clashes.

Pitfalls

  • A switch that misses a new case. In a language without exhaustiveness checks, a function over the cases returns a default value or nothing for a new case. The wrong blocks in the Python and JavaScript files show this. End every such function with a branch that raises an error.
  • A default branch in an exhaustive match. A _ or default arm turns off the check that would find the missing case when someone adds a variant. Leave it out when the cases are meant to be closed.
  • Static binding mistaken for dispatch. Extension methods in C# and Kotlin, and overloads in Java, choose code by the static type of the argument, so an overload for a new case does not run through a variable of the base type. The wrong block in the C# file shows this.
  • Name clashes in open extension. Two modules that add a method of the same name to the same class overwrite each other. Use symbols, namespaced names or traits with coherence rules.
  • The orphan rule. In Rust, code cannot implement a trait from one crate for a type from another. Wrap the type in a local newtype. The failing block in the Rust file shows the error.
  • Choosing the wrong side. Most data types grow mainly in one direction. Pick the layout that makes the common change local: classes for a set of plug-ins that grows, a closed sum type for a syntax tree that many passes read.

Cost

The mechanisms differ little in run time. A virtual call or an interface call costs an indirect jump, and a match on a sum type costs a jump through a table or a short series of comparisons. A visitor costs two indirect calls for each node. A registry such as singledispatch costs a lookup in a dictionary, which it caches. Generic solutions with traits or type parameters cost nothing at run time when the compiler specializes them, but they increase compile time and code size. The larger cost is in maintenance: the side that a design closes decides how many files a common change touches.

History

Cases and operations as two dimensions of a program appear in John Reynolds's 1975 paper on user-defined types and procedural data structures, which compared abstract data types with procedural data abstraction, the style of objects. William Cook returned to the comparison in 1990, and Shriram Krishnamurthi, Matthias Felleisen and Daniel Friedman described the extensibility problem and an extension of the visitor pattern in 1998. Philip Wadler gave the problem its name in a message to the java-genericity mailing list on 12 November 1998, writing that "The Expression Problem is a new name for an old problem", and proposed a solution in Generic Java.1

Many solutions followed. Martin Odersky and Matthias Zenger solved it in Scala with abstract types and mixins in 2005, Bruno Oliveira and William Cook proposed object algebras in 2012, and the tagless final style of Jacques Carette, Oleg Kiselyov and Chung-chieh Shan used type classes. Clojure added protocols in version 1.2 in 2010, with the expression problem as a stated motivation.3 The coherence rules of Rust traits answer a part of the same question: which crate may add the code for a given pair of trait and type.2

References

  1. Philip Wadler, The Expression Problem, message to the java-genericity mailing list, 12 November 1998, The opening paragraphs
  2. Implementations, The Rust Reference, Trait implementation coherence; Orphan rules
  3. Protocols, Clojure Reference, Motivation

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/656G08/text.yaml