1 using FxSharp.Extensions;
2 using JetBrains.Annotations;
4 using System.Collections.Generic;
12 public static class Maybe
22 public static Maybe<T> ToMaybe<T>(
this T val)
25 if (typeof (T).IsValueType)
43 public static IEnumerable<T> ToEnumerable<T>(
this Maybe<T> maybe)
46 just: t => t.ToEnumerable(),
47 nothing: Enumerable.Empty<T>);
55 public static bool IsJust<T>(
this Maybe<T> maybe)
59 nothing: () =>
false);
67 public static bool IsNothing<T>(
this Maybe<T> maybe)
80 public static Maybe<T> Just<T>(T val)
82 return new Maybe<T>(val);
90 public static Maybe<T> Nothing<T>()
92 return new Maybe<T>();
100 public struct Maybe<T>
106 private readonly
bool _hasValue;
111 private readonly T _val;
117 internal Maybe(T val)
138 return _hasValue ? _val : other;
155 public Maybe<TResult> Select<TResult>([NotNull] Func<T, TResult> fn)
158 ?
new Maybe<TResult>(fn(_val))
159 :
new Maybe<TResult>();
194 public Maybe<TResult> SelectMany<TResult>([NotNull] Func<T, Maybe<TResult>> fn)
196 return _hasValue ? fn(_val) :
new Maybe<TResult>();
218 public Maybe<TResult> SelectMany<TInter, TResult>(
219 [NotNull] Func<T, Maybe<TInter>> firstFn,
220 [NotNull] Func<T, TInter, TResult> secondFn)
222 return SelectMany(x => firstFn(x).SelectMany(y => secondFn(x, y).ToMaybe()));
265 public TResult Match<TResult>(
266 [NotNull] Func<TResult> nothing,
267 [NotNull] Func<T, TResult> just)
269 return _hasValue ? just(_val) : nothing();
307 return _hasValue ? string.Format(
"Just {0}", _val) :
"Nothing";
Maybe< T > Match_([NotNull] Action nothing, [NotNull] Action< T > just)
Map either the function just over the present val or call nothing. Ignore the result.
A type to describe a possibly absent val.
T GetOrElse(T other)
Get the stored val or the given default instead.
Maybe< T > Otherwise_([NotNull] Action fn)
Call the given function, if no val is present.
Maybe< T > Select_([NotNull] Action< T > fn)
Map the function fn over the wrapped val if present; discard the result.
override string ToString()