On Tuesday, 10 December 2013 at 20:35:08 UTC, Namespace wrote:
I love Monadic null checking. Would be great if D would have it.

Doesn't need to be a language feature - you can implement it as a library type. Here's a quick hacked together maybe monad:

----
import std.stdio;

struct Maybe(T)
{
    private T val = null;

    this(T t)
    {
        val = t;
    }

    auto opDispatch(string method, U...)(U params)
    {
        alias typeof(mixin("val." ~ method ~ "(params)")) retType;
        if (val) {
mixin("return Maybe!(" ~ retType.stringof ~ ")(val." ~ method ~ "(params));");
        }
        return nothing!retType();
    }
}

Maybe!T just(T)(T t)
{
    return Maybe!T(t);
}

Maybe!T nothing(T)()
{
    return Maybe!T();
}

class Foo
{
    Bar retNull()
    {
        writeln("foo null");
        return null;
    }

    Bar notNull()
    {
        writeln("foo not null");
        return new Bar();
    }
}

class Bar
{
    Foo retNull()
    {
        writeln("bar null");
        return null;
    }

    Foo notNull()
    {
        writeln("bar not null");
        return new Foo();
    }
}

void main()
{
    auto maybe = just(new Foo);
    maybe.notNull().notNull().notNull().retNull().notNull();
}

----

Reply via email to