sumtype 0.2.0

A sum type with pattern matching


To use this package, put the following dependency into your project's dependencies section:

dub.json
dub.sdl

sumtype

A sum type for modern D.

Features

  • Pattern matching.
  • Self-referential types (This).
  • Full attribute correctness—pure, @safe, @nogc, and nothrow when applicable.
  • No runtime dependency on TypeInfo.
  • No heap allocation/boxing.

Documentation

Example

import std.typecons: Tuple, tuple;

struct Nil {}
alias List = SumType!(
    Nil,
    Tuple!(int, "head", This*, "tail")
);
alias Cons = Tuple!(int, "head", List*, "tail");

List* nil()
{
    return new List(Nil());
}

List* cons(int item, List* l)
{
    return new List(Cons(item, l));
}

List* list(int[] items...)
{
    if (items.length == 0)
        return nil;
    else
        return cons(items[0], list(items[1..$]));
}

int sum(List l)
{
    return l.match!(
        (Nil _) => 0,
        (Cons cons) => cons.head + sum(*cons.tail)
    );
}

List* myList = list(1, 2, 3, 4, 5);

assert(sum(*myList) == 15);


Installation

If you're using dub, add the sumtype package to your project as a dependency.

Alternatively, since it's a single, self-contained module, you can simply copy sumtype.d to your source directory and compile as usual.

Authors:
Paul Backus
Dependencies:
none
Versions:
0.2.0 2018-Apr-10
0.1.1 2018-Apr-09
0.1.0 2018-Apr-05
~master 2018-Apr-14
Show all 4 versions
Download Stats:
  • 0 downloads today

  • 0 downloads this week

  • 2 downloads this month

  • 2 downloads total

Score:
0.6