Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template isNullableType(T) {
- enum isNullableType = __traits(compiles, T.init is null);
- }
- struct Option(T) {
- private:
- static if (isNullableType!T) {
- T _value;
- pure @safe nothrow
- this(T value) {
- _value = value;
- }
- } else {
- T _value;
- bool _isSome;
- pure @safe nothrow
- this(T value) {
- _value = value;
- _isSome = true;
- }
- }
- public:
- pure @safe nothrow
- bool isNone() const {
- static if (isNullableType!T) {
- return _value is null;
- } else {
- return !_isSome;
- }
- }
- pure @safe
- inout(T) get() inout {
- if (isNone) {
- throw new Exception("get called on an empty Option type!");
- }
- return _value;
- }
- @trusted
- string toString() const {
- import std.conv;
- if (isNone) {
- return "None";
- } else {
- return "Some(" ~ to!string(_value) ~ ")";
- }
- }
- }
- pure @safe nothrow
- Option!T none(T)()
- out(val) {
- assert(val.isNone);
- } body {
- return Option!T.init;
- }
- pure @safe nothrow
- inout(Option!T) some(T)(inout(T) value)
- out(val) {
- assert(!val.isNone);
- } body {
- return Option!T(value);
- }
- auto map(alias fun, T)(Option!T option) {
- alias typeof(fun(option._value)) R;
- if (!option.isNone) {
- return some(fun(option._value));
- }
- return none!R();
- }
- auto otherwise(T, TC)(Option!T option, lazy TC alternative)
- if(is(TC : T)) {
- if (!option.isNone) {
- return option._value;
- }
- return alternative();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement