-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEither.cs
61 lines (52 loc) · 1.21 KB
/
Either.cs
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
59
60
61
class Either<Right, Left>
{
readonly Right right;
readonly Left left;
readonly bool isRight = true;
public Either(Right val)
{
right = val;
}
public Either(Left val)
{
left = val;
isRight = false;
}
public Either<T, Left> Map<T>(Func<Right, T> mapping)
{
if (isRight)
{
var result = mapping(right);
return new Either<T, Left>(result);
}
return new Either<T, Left>(left);
}
public Either<T, Left> Bind<T>(Func<Right, Either<T, Left>> binding)
{
return isRight ? binding(right) : new Either<T, Left>(left);
}
public override string ToString()
{
return isRight
? "Right(" + right.ToString() + ")"
: "Left(" + left.ToString() + ")";
}
}
var five = new Either<int, string>(2)
.Map(x => x + 3)
.ToString();
//Right(5)
Either<int, string> Divide(int numerator, int denominator)
{
return denominator == 0
? new Either<int, string>("cannot divide by 0")
: new Either<int, string>(numerator / denominator);
}
var divByZero = new Either<int, string>(10)
.Bind(x => Divide(x, 0))
.ToString();
//Left(cannot divide by 0)
var fiveAgain = new Either<int, string>(10)
.Bind(x => Divide(x, 2))
.ToString();
//Right(5)