Skip to content

Instantly share code, notes, and snippets.

@atilaneves
Created April 20, 2015 15:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atilaneves/727d63f0a7029032d7ac to your computer and use it in GitHub Desktop.
Save atilaneves/727d63f0a7029032d7ac to your computer and use it in GitHub Desktop.
Maybe monad in D
import std.stdio;
import std.traits;
import std.conv;
@safe:
struct Maybe(T) {
T payload;
private bool _just;
}
auto just(T)(T t) pure nothrow {
return Maybe!T(t, true);
}
auto nothing(T)() pure nothrow {
return Maybe!T(T.init, false);
}
auto bind(alias F, T)(auto ref Maybe!T maybe) {
return maybe._just ? F(maybe.payload) : nothing!T;
}
class MyClass {
private int i;
this(int i) pure nothrow const { this.i = i;}
override string toString() pure const { return "MyClass(" ~ i.to!string ~ ")";}
}
void main() {
writeln("value of Just(5): ", just(5).bind!(a => just(a * 2)).bind!(a => just(a * 3)));
writeln("value of Nothing: ", nothing!int.bind!(a => just(a * 2)).bind!(a => just(a * 3)));
writeln("just class: ", just(new MyClass(5)).bind!(a => just(new MyClass(a.i * 2))).bind!(a => just(new MyClass(a.i * 3))));
MyClass oops; //null
writeln("noth class: ", nothing!MyClass.bind!(a => just(new MyClass(a.i * 2))).bind!(a => just(new MyClass(a.i * 3))));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment