forked from NoelKennedy/scalesque
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Option.cs
383 lines (342 loc) · 12.9 KB
/
Option.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Scalesque {
/// <summary>
/// Represents an optional value. Is either a <see cref="Some<T>"/> or a <see cref="None<T>"/> representing value present or missing respectively.
/// </summary>
/// <typeparam name="T"><T> The type of the optional value</typeparam>
public abstract partial class Option<T> : IEnumerable<T> {
/// <summary>
/// Gets if the optional value is missing
/// </summary>
public abstract bool IsEmpty { get; }
/// <summary>
/// Gets if the optional value is present
/// </summary>
public bool HasValue { get { return !IsEmpty; } }
/// <summary>
/// Gets the optional value if it is there or throws exception.
/// Internal so that safer methods are forced on the user
/// </summary>
/// <returns>T</returns>
internal abstract T Get();
/// <summary>
/// Maps the type of an optional value from <T> to a <U>
/// </summary>
/// <typeparam name="U"></typeparam>
/// <param name="f"></param>
/// <returns></returns>
public Option<U> Map<U>(Func<T, U> f) {
if (IsEmpty)
return None<U>.apply();
return new Some<U>(f(Get()));
}
/// <summary>
/// Maps the type of an optional value from <T> to a <U>
/// Safe means that if an exception is encountered, then it will return None
/// </summary>
/// <typeparam name="U"></typeparam>
/// <param name="f"></param>
/// <returns></returns>
public Option<U> SafeMap<U>(Func<T, U> f) {
if (IsEmpty)
return None<U>.apply();
return Option.safeApply(()=>f(Get()));
}
/// <summary>
/// Gets the value if it exists, else a default value. Lazy evaulation of default value.
/// </summary>
/// <param name="f">Func<T> Allows lazy evaluation. f will only be evaluated if the Option is None</param>
/// <returns>T</returns>
public T GetOrElse(Func<T> f) {
if (IsEmpty)
return f();
return Get();
}
/// <summary>
/// Gets the value if it exists, else a default value. No lazy evaluation of default value.
/// </summary>
/// <param name="default">T the default value. This is evaluated regardless of whether it is used or not</param>
/// <returns>T</returns>
public T GetOrElse(T @default) {
return IsEmpty ? @default : Get();
}
/// <summary>
/// Flattens the value and maps it to an Option<U>
/// </summary>
/// <typeparam name="U"></typeparam>
/// <param name="f"></param>
/// <returns></returns>
public Option<U> FlatMap<U>(Func<T, Option<U>> f) {
if (IsEmpty)
return Option.None();
return f(Get());
}
/// <summary>
/// Opposite of flatMap. Keeps the value if this is Some<T>, else returns the Option<T> of the function.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public Option<T> Or(Func<Option<T>> f) {
if (HasValue)
return this;
return f();
}
/// <summary>
/// Returns result of ifEmpty if is <see cref="None<T>"/> or passes value to f and returns result
/// </summary>
/// <typeparam name="Y"></typeparam>
/// <param name="ifEmpty"></param>
/// <param name="f"></param>
/// <returns>Y</returns>
public Y Fold<Y>(Func<Y> ifEmpty, Func<T,Y> f) {
if (IsEmpty)
return ifEmpty();
return f(Get());
}
/// <summary>
/// Implements applicative functor for Option<T>
/// </summary>
/// <typeparam name="U"></typeparam>
/// <param name="tf">Func<T,U> tf a function inside the 'context' of an Option which to be applied to this Option</param>
/// <returns>Option<U> Some<U> if both original Options are Some, else None<U></returns>
public Option<U> Applicative<U>(Option<Func<T,U>> tf) {
return tf.FlatMap(Map);
}
public IEnumerator<T> GetEnumerator() {
if (IsEmpty)
return new List<T>().GetEnumerator();
return new List<T> {Get()}.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
/// <summary>
/// More natural pattern matching for Option
/// option.Match(
/// Some: x=>fn(x),
/// None: ()=>fn()
/// )
/// </summary>
/// <typeparam name="R">Result Type</typeparam>
/// <param name="Some">Function used if the option is a Some</param>
/// <param name="None">Function used if the option is a None</param>
/// <returns>The resultant value from the applied function.</returns>
public R Match<R>(Func<T, R> Some, Func<R> None) {
return HasValue ? Some(Get()): (None == null ? default(R) : None());
}
/// <summary>
/// More natural pattern matching for Option
/// option.Match(
/// Some: x=>fn(x),
/// None: ()=>fn()
/// )
/// with no return type
/// </summary>
/// <param name="Some">Function used if the option is a Some</param>
/// <param name="None">Function used if the option is a None</param>
public void Match(Action<T> Some, Action None)
{
Match<Unit>(
Some: x =>
{
Some(x);
return Unit.Value;
},
None: () =>
{
None();
return Unit.Value;
});
}
/// <summary>
/// Apply the given method to the option's value, if it is nonempty. Otherwise, do nothing.
/// </summary>
/// <param name="ifSome">Action to perform if there is a value (Some)</param>
public void ForEach(Action<T> ifSome)
{
Match<Unit>(
Some: x =>
{
ifSome(x);
return Unit.Value;
},
None: () => Unit.Value);
}
}
/// <summary>
/// Represents a missing optional value
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class None<T> : Option<T> {
public override bool IsEmpty {
get { return true; }
}
internal override T Get() {
throw new ArgumentNullException("Get called on None");
}
public static Option<T> apply() {
return new None<T>();
}
private None() {}
public override string ToString() {
return "None";
}
/// <summary>
/// Option equality that checks against the two different None types
/// </summary>
/// <param name="obj">Object to compare this object against</param>
/// <returns>True if None, else False</returns>
public override bool Equals(object obj) {
return Option.IsNone(obj);
}
}
/// <summary>
/// Represents a present optional value
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class Some<T> : Option<T> {
private readonly T value;
public Some(T value) {
this.value = value;
}
public override bool IsEmpty {
get { return false; }
}
internal override T Get() {
return value;
}
public override string ToString() {
return "Some(" + value + ")";
}
/// <summary>
/// Option equality checks if it is a Some, if so compares the wrapped values
/// </summary>
/// <param name="obj">Object to compare this object against</param>
/// <returns>True if obj is a Some and values are equal, otherwise False</returns>
public override bool Equals(object obj) {
if (obj == null) return false;
if (Option.IsNone(obj)) return false;
var objAsSome = obj as Some<T>;
return objAsSome != null && value.Equals(objAsSome.value);
}
}
/// <summary>
/// Companion class for Option
/// </summary>
public static class Option {
/// <summary>
/// Check whether the given object is a None (comparing against both possibilities)
/// </summary>
/// <param name="obj">Object to verify</param>
/// <returns>True if None, otherwise False</returns>
public static Boolean IsNone(Object obj) {
if (obj == null)
return false;
if (obj is None) return true;
return typeof(None<>) == obj.GetType().GetGenericTypeDefinition();
}
/// <summary>
/// Creates an <see cref="Option{T}"/>. Result be <see cref="Some{T}"/> if the reference is not null else will be <see cref="None{T}"/>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static Option<T> apply<T>(T value) {
if (value == null)
return None();
return new Some<T>(value);
}
/// <summary>
/// Creates an <see cref="Option{T}"/>. Result be <see cref="Some{T}"/> if the reference is not null AND doesn't throw an exception else will be <see cref="None{T}"/>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static Option<T> safeApply<T>(Func<T> value) {
if (value == null)
return None();
T val;
try {
val = value();
}
catch {
return None();
}
if (val == null)
return None();
return new Some<T>(val);
}
/// <summary>
/// Converts a reference to T an <see cref="Option{T}"/>. Result be <see cref="Some{T}"/> if the reference is not null else will be <see cref="None{T}"/>.
///
/// Implicit method for <see cref="Option.apply{T}"/>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static Option<T> Opt<T>(this T value) {
return apply(value);
}
public static Option<T> Opt<T>(this Nullable<T> value) where T:struct {
if (value.HasValue)
return apply(value.Value);
return None();
}
/// <summary>
/// Flattens an IEnumerable<Option<T>> to a IEnenumerable<T>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumerable"></param>
/// <returns></returns>
public static IEnumerable<T> Flatten<T>(this IEnumerable<Option<T>> enumerable) {
return from option in enumerable where option.HasValue select option.Get();
}
/// <summary>
/// Returns the first value from the enumerable.
/// None if the enumerable is empty
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumerable"></param>
/// <returns></returns>
public static Option<T> FirstOption<T>(this IEnumerable<T> enumerable) {
return safeApply(()=> enumerable.FirstOrDefault());
}
/// <summary>
/// Convenience method for creating None<T>
/// </summary>
/// <returns>None. implicitly converted to None<T></returns>
public static None None() {
return new None();
}
/// <summary>
/// Constructs a Some<T> from a variable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static Option<T> Some<T>(T value) {
return apply(value);
}
/// <summary>
/// Constructs a Some<T> from a T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static Some<T> ToSome<T>(this T value) {
return new Some<T>(value);
}
/// <summary>
/// Constructs a None<T> from a T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static Option<T> ToNone<T>(this T value) {
return None();
}
}
}