Skip to content

Instantly share code, notes, and snippets.

@stijnmoreels
Created February 14, 2018 13:51
Show Gist options
  • Save stijnmoreels/be6eb911be942d09381aa4c3eba3d6db to your computer and use it in GitHub Desktop.
Save stijnmoreels/be6eb911be942d09381aa4c3eba3d6db to your computer and use it in GitHub Desktop.
Maybe class
namespace System.Monads
{
public class Maybe<TA>
{
private readonly TA _value;
private bool IsPresent => _value != null;
private Maybe() { _value = default(TA); }
private Maybe(TA value) { _value = value; }
public static Maybe<T> Just<T>(T x) => new Maybe<T>(x);
public static Maybe<TA> Nothing => new Maybe<TA>();
public Maybe<TB> SelectMany<TB>(Func<TA, Maybe<TB>> f) => IsPresent ? f(_value) : Maybe<TB>.Nothing;
public Maybe<TA> Where(Func<TA, bool> f) => IsPresent && f(_value) ? this : Nothing;
public Maybe<TB> Select<TB>(Func<TA, TB> f) => IsPresent ? Maybe<TB>.Just(f(_value)) : Maybe<TB>.Nothing;
public TA GetOrElse(TA otherwise) => IsPresent ? _value : otherwise;
public TA GetOrElse(Lazy<TA> otherwise) => IsPresent ? _value : otherwise.Value;
public Maybe<TA> OrElse(Maybe<TA> other) => IsPresent ? this : other;
public Maybe<TA> Do(Action<TA> f)
{
if (IsPresent) { f(_value); }
return this;
}
}
public static class MaybeExtensions
{
public static Maybe<TA> Flatten<TA>(this Maybe<Maybe<TA>> x) => x.GetOrElse(Maybe<TA>.Nothing);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment