-
Notifications
You must be signed in to change notification settings - Fork 1
/
maybe.d
58 lines (51 loc) · 1.1 KB
/
maybe.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
module util.maybe;
struct Maybe(T){
private T payload;
private bool _exists;
bool opCast(T:bool)(){ return _exists; }
this(T payload){
this.payload=payload;
_exists=true;
}
ref T get()in{
assert(!!this);
}do{
return payload;
}
void opAssign(Maybe!T rhs){
this.payload=rhs.payload;
this._exists=rhs._exists;
}
void opAssign(T rhs){
this.payload=rhs;
this._exists=true;
}
void clear(){ this=typeof(this).init; }
string toString()(){
import std.conv:text;
if(_exists) return text("just(",payload,")");
return "none!"~T.stringof;
}
}
Maybe!T none(T)(){ return Maybe!T(); }
Maybe!T just(T)(T arg){ return Maybe!T(arg); }
template mfold(alias yes,alias no){
auto mfold(T)(auto ref Maybe!T arg){
if(arg._exists) return yes(arg.payload);
else return no();
}
}
template mmap(alias f){
auto mmap(T)(auto ref Maybe!T arg){
return arg.fold!(x=>just(f(x)),()=>none!(typeof(f(arg.payload))));
}
}
Maybe!T mjoin(T)(Maybe!(Maybe!T) arg){
if(arg._exists) return arg.payload;
return none!T;
}
template mbind(alias f){
auto mbind(T)(auto ref Maybe!T arg){
return arg.map!f.join;
}
}