blob: 122a49304507630c95b846ebacb5805a0240935a (
plain)
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
62
63
|
using System;
class Maybe<T>
{
public readonly static Maybe<T> Nothing = new Maybe<T> ();
public T Value { get; private set; }
public bool HasValue { get; private set; }
Maybe ()
{
HasValue = false;
}
public Maybe (T value)
{
Value = value;
HasValue = true;
}
public override string ToString ()
{
if (HasValue)
return Value.ToString ();
return string.Empty;
}
public Maybe<U> SelectMany<U> (Func<T, Maybe<U>> k)
{
if (!HasValue)
return Maybe<U>.Nothing;
return k (Value);
}
public Maybe<V> SelectMany<U, V> (
Func<T, Maybe<U>> selector,
Func<T, U, V> resultSelector)
{
if (!HasValue)
return Maybe<V>.Nothing;
Maybe<U> n = selector (Value);
if (!n.HasValue)
return Maybe<V>.Nothing;
return resultSelector (Value, n.Value).ToMaybe ();
}
}
static class MaybeExtensions
{
public static Maybe<T> ToMaybe<T> (this T value)
{
return new Maybe<T> (value);
}
}
class Test
{
public static void Main ()
{
Console.WriteLine (
from x in 1.ToMaybe ()
from y in 2.ToMaybe ()
from z in 3.ToMaybe ()
select x + y + z);
}
}
|