Giter Site home page Giter Site logo

sumtype's Introduction

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.

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.