-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaybe.cs
More file actions
77 lines (68 loc) · 2.52 KB
/
Copy pathMaybe.cs
File metadata and controls
77 lines (68 loc) · 2.52 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
namespace MondadsInCsharp
{
/// <summary>
/// Value representing a maybe result.
/// </summary>
/// <typeparam name="T">The type of the maybe value</typeparam>
public abstract class Maybe<T> { }
/// <summary>
/// Result that contains no value.
/// </summary>
/// <typeparam name="T"></typeparam>
public class Nothing<T> : Maybe<T> { }
/// <summary>
/// Result that contains a value.
/// </summary>
/// <typeparam name="T"></typeparam>
public class Just<T> : Maybe<T>
{
public T Value { get; }
public Just(T value)
{
Value = value;
}
}
public static class MaybeExtensions
{
public static Maybe<TOut> fmap<TIn, TOut>(this Maybe<TIn> maybe, Func<TIn, TOut> func)
{
switch (maybe)
{
case Nothing<TIn> _: return new Nothing<TOut>();
case Just<TIn> just: return new Just<TOut>(func(just.Value));
default: throw new Exception("Do not derive from Maybe yourself!");
}
}
public static Maybe<TOut> fmap<TIn, TOut>(this Func<TIn, TOut> func, Maybe<TIn> maybe) => maybe.fmap(func);
public static Maybe<TOut> ab<TArg, TOut>(this Maybe<Func<TArg, TOut>> maybe, Maybe<TArg> maybe_arg)
{
switch (maybe)
{
case Nothing<Func<TArg, TOut>> _: return new Nothing<TOut>();
case Just<Func<TArg, TOut>> just:
switch (maybe_arg)
{
case Nothing<TArg> _: return new Nothing<TOut>();
case Just<TArg> arg:
return new Just<TOut>(just.Value(arg.Value));
default: throw new Exception("Do not derive from Maybe yourself!");
}
default: throw new Exception("Do not derive from Maybe yourself!");
}
}
public static Maybe<TOut> bind<TIn, TOut>(this Maybe<TIn> maybe, Func<TIn, Maybe<TOut>> func)
{
switch (maybe)
{
case Nothing<TIn> _: return new Nothing<TOut>();
case Just<TIn> just: return func(just.Value);
default: throw new Exception("Do not derive from Maybe yourself!");
}
}
public static Maybe<T> pureMaybe<T>(this T value)
{
return new Just<T>(value);
}
}
}