sumtype 0.5.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, including support for structural matching
- Self-referential types, using
This
- Works with
pure
,@safe
,@nogc
,nothrow
, andimmutable
- Zero runtime overhead compared to hand-written C
- No heap allocation
- Does not rely on runtime type information (
TypeInfo
)
Documentation
sumtype
uses adrdox to generate its documentation. To build your own
copy, run the following command from the root of the sumtype
repository:
path/to/adrdox/doc2 --genSearchIndex --genSource -o generated-docs src
Example
import std.math: approxEqual, cos, PI, sqrt;
struct Rectangular { double x, y; }
struct Polar { double r, theta; }
alias Vector = SumType!(Rectangular, Polar);
pure @safe @nogc nothrow
double length(Vector v)
{
return v.match!(
rect => sqrt(rect.x^^2 + rect.y^^2),
polar => polar.r
);
}
pure @safe @nogc nothrow
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).approxEqual(sqrt(2.0)));
assert(length(v).approxEqual(1));
assert(horiz(u).approxEqual(1));
assert(horiz(v).approxEqual(sqrt(0.5)));
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.
- Registered by Paul Backus
- 0.5.0 released 6 months ago
- pbackus/sumtype
- MIT
- Copyright © 2018, Paul Backus
- Authors:
- Dependencies:
- none
- Versions:
-
0.8.0 2019-Jan-14 0.7.1 2018-Dec-13 0.7.0 2018-Nov-20 0.6.4 2018-Nov-15 0.6.3 2018-Nov-14 - Download Stats:
-
-
24 downloads today
-
120 downloads this week
-
492 downloads this month
-
3980 downloads total
-
- Score:
- 3.6
- Short URL:
- sumtype.dub.pm