Created
April 20, 2015 15:36
-
-
Save atilaneves/727d63f0a7029032d7ac to your computer and use it in GitHub Desktop.
Maybe monad in D
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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