Skip to content

Instantly share code, notes, and snippets.

@CoditCompany
Last active August 24, 2017 08:00
Show Gist options
  • Select an option

  • Save CoditCompany/be8f5affd5bda3dccd7a5533237d62af to your computer and use it in GitHub Desktop.

Select an option

Save CoditCompany/be8f5affd5bda3dccd7a5533237d62af to your computer and use it in GitHub Desktop.
/// <summary>
/// Type to indicate that there might be a value missing.
/// </summary>
/// <typeparam name="TA">The type of a.</typeparam>
public class Maybe<TA>
{
private TA _value;
private bool IsPresent => _value != null;
/// <summary>
/// Prevents a default instance of the <see cref="Maybe{T}"/> class from being created.
/// </summary>
private Maybe() { }
/// <summary>
/// Gets nothing.
/// </summary>
/// <value>The nothing.</value>
public static Maybe<TA> Nothing => new Maybe<TA>();
/// <summary>
/// Just the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static Maybe<TA> Just(TA value) => new Maybe<TA>() {_value = value};
/// <summary>
/// Executes the given <paramref name="f"/> when there's a value present for the current <see cref="Maybe{TA}"/>.
/// </summary>
/// <typeparam name="TB">The type of the b.</typeparam>
/// <param name="f">The f.</param>
/// <returns></returns>
public Maybe<TB> Bind<TB>(Func<TA, Maybe<TB>> f) => IsPresent ? f(_value) : Maybe<TB>.Nothing;
/// <summary>
/// Filter on the wrapped value inside the <see cref="Maybe{TA}"/> by using the given <paramref name="predicate"/>.
/// </summary>
/// <param name="predicate">The predicate.</param>
/// <returns></returns>
public Maybe<TA> Where(Func<TA, bool> predicate) => Bind(x => predicate(x) ? this : Nothing);
/// <summary>
/// Maps the wrapped value inside the <see cref="Maybe{TA}"/> with the given <paramref name="f"/> to a new value <see cref="TB"/> if there's a value present for the current <see cref="Maybe{TA}"/>.
/// </summary>
/// <typeparam name="TB">The type of the b.</typeparam>
/// <param name="f">The f.</param>
/// <returns></returns>
public Maybe<TB> Select<TB>(Func<TA, TB> f) => Bind(x => Maybe<TB>.Just(f(_value)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment