sumtype

SumType is a generic discriminated union implementation that uses design-by-introspection to generate safe and efficient code. Its features include:

  • Pattern matching.
  • Support for self-referential types.
  • Full attribute correctness (pure, @safe, @nogc, and nothrow are inferred whenever possible).
  • A type-safe and memory-safe API compatible with DIP 1000 (scope).
  • No dependency on runtime type information (TypeInfo).
  • Compatibility with BetterC.

Members

Classes

MatchException
class MatchException

Thrown by tryMatch when an unhandled type is encountered.

Structs

SumType
struct SumType(Types...)

A tagged union that can hold a single value from any of a specified set of types.

This
struct This

Placeholder used to refer to the enclosing SumType.

Templates

canMatch
template canMatch(alias handler, Ts...)

True if handler is a potential match for Ts, otherwise false.

isSumType
template isSumType(T)

True if T is a SumType or implicitly converts to one, otherwise false.

match
template match(handlers...)

Calls a type-appropriate function with the value held in a SumType.

tryMatch
template tryMatch(handlers...)

Attempts to call a type-appropriate function with the value held in a SumType, and throws on failure.

Examples

import std.math: isClose;

struct Fahrenheit { double degrees; }
struct Celsius { double degrees; }
struct Kelvin { double degrees; }

alias Temperature = SumType!(Fahrenheit, Celsius, Kelvin);

// Construct from any of the member types.
Temperature t1 = Fahrenheit(98.6);
Temperature t2 = Celsius(100);
Temperature t3 = Kelvin(273);

// Use pattern matching to access the value.
Fahrenheit toFahrenheit(Temperature t)
{
    return Fahrenheit(
        t.match!(
            (Fahrenheit f) => f.degrees,
            (Celsius c) => c.degrees * 9.0/5 + 32,
            (Kelvin k) => k.degrees * 9.0/5 - 459.4
        )
    );
}

assert(toFahrenheit(t1).degrees.isClose(98.6));
assert(toFahrenheit(t2).degrees.isClose(212));
assert(toFahrenheit(t3).degrees.isClose(32));

// Use ref to modify the value in place.
void freeze(ref Temperature t)
{
    t.match!(
        (ref Fahrenheit f) => f.degrees = 32,
        (ref Celsius c) => c.degrees = 0,
        (ref Kelvin k) => k.degrees = 273
    );
}

freeze(t1);
assert(toFahrenheit(t1).degrees.isClose(32));

// Use a catch-all handler to give a default result.
bool isFahrenheit(Temperature t)
{
    return t.match!(
        (Fahrenheit f) => true,
        _ => false
    );
}

assert(isFahrenheit(t1));
assert(!isFahrenheit(t2));
assert(!isFahrenheit(t3));

Introspection-based matching

In the length and horiz functions below, the handlers for match do not specify the types of their arguments. Instead, matching is done based on how the argument is used in the body of the handler: any type with x and y properties will be matched by the rect handlers, and any type with r and theta properties will be matched by the polar handlers.

import std.math: isClose, cos, PI, sqrt;

struct Rectangular { double x, y; }
struct Polar { double r, theta; }
alias Vector = SumType!(Rectangular, Polar);

double length(Vector v)
{
    return v.match!(
        rect => sqrt(rect.x^^2 + rect.y^^2),
        polar => polar.r
    );
}

double horiz(Vector v)
{
    return v.match!(
        rect => rect.x,
        polar => polar.r * cos(polar.theta)
    );
}

Vector u = Rectangular(1, 1);
Vector v = Polar(1, PI/4);

assert(length(u).isClose(sqrt(2.0)));
assert(length(v).isClose(1));
assert(horiz(u).isClose(1));
assert(horiz(v).isClose(sqrt(0.5)));

Arithmetic expression evaluator

This example makes use of the special placeholder type This to define a recursive data type: an abstract syntax tree for representing simple arithmetic expressions.

1 import std.functional: partial;
2 import std.traits: EnumMembers;
3 import std.typecons: Tuple;
4 
5 enum Op : string
6 {
7     Plus  = "+",
8     Minus = "-",
9     Times = "*",
10     Div   = "/"
11 }
12 
13 // An expression is either
14 //  - a number,
15 //  - a variable, or
16 //  - a binary operation combining two sub-expressions.
17 alias Expr = SumType!(
18     double,
19     string,
20     Tuple!(Op, "op", This*, "lhs", This*, "rhs")
21 );
22 
23 // Shorthand for Tuple!(Op, "op", Expr*, "lhs", Expr*, "rhs"),
24 // the Tuple type above with Expr substituted for This.
25 alias BinOp = Expr.Types[2];
26 
27 // Factory function for number expressions
28 Expr* num(double value)
29 {
30     return new Expr(value);
31 }
32 
33 // Factory function for variable expressions
34 Expr* var(string name)
35 {
36     return new Expr(name);
37 }
38 
39 // Factory function for binary operation expressions
40 Expr* binOp(Op op, Expr* lhs, Expr* rhs)
41 {
42     return new Expr(BinOp(op, lhs, rhs));
43 }
44 
45 // Convenience wrappers for creating BinOp expressions
46 alias sum  = partial!(binOp, Op.Plus);
47 alias diff = partial!(binOp, Op.Minus);
48 alias prod = partial!(binOp, Op.Times);
49 alias quot = partial!(binOp, Op.Div);
50 
51 // Evaluate expr, looking up variables in env
52 double eval(Expr expr, double[string] env)
53 {
54     return expr.match!(
55         (double num) => num,
56         (string var) => env[var],
57         (BinOp bop) {
58             double lhs = eval(*bop.lhs, env);
59             double rhs = eval(*bop.rhs, env);
60             final switch(bop.op) {
61                 static foreach(op; EnumMembers!Op) {
62                     case op:
63                         return mixin("lhs" ~ op ~ "rhs");
64                 }
65             }
66         }
67     );
68 }
69 
70 // Return a "pretty-printed" representation of expr
71 string pprint(Expr expr)
72 {
73     import std.format;
74 
75     return expr.match!(
76         (double num) => "%g".format(num),
77         (string var) => var,
78         (BinOp bop) => "(%s %s %s)".format(
79             pprint(*bop.lhs),
80             cast(string) bop.op,
81             pprint(*bop.rhs)
82         )
83     );
84 }
85 
86 Expr* myExpr = sum(var("a"), prod(num(2), var("b")));
87 double[string] myEnv = ["a":3, "b":4, "c":7];
88 
89 assert(eval(*myExpr, myEnv) == 11);
90 assert(pprint(*myExpr) == "(a + (2 * b))");

Meta

License

Boost License 1.0

Authors

Paul Backus