Skip to content

Instantly share code, notes, and snippets.

@ElemarJR
Created October 20, 2016 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElemarJR/6ca474d3afdede72688dda3c2d77c62f to your computer and use it in GitHub Desktop.
Save ElemarJR/6ca474d3afdede72688dda3c2d77c62f to your computer and use it in GitHub Desktop.
using System;
namespace JLang.Functional
{
using static Helpers;
public struct Option<T>
{
internal T Value { get; }
public bool IsSome { get; }
public bool IsNone => !IsSome;
internal Option(T value, bool isSome)
{
Value = value;
IsSome = isSome;
}
public TR Match<TR>(Func<T, TR> Some, Func<TR> None)
=> IsSome ? Some(Value) : None();
public static readonly Option<T> None = new Option<T>();
public static implicit operator Option<T>(T value)
=> Some(value);
public static implicit operator Option<T>(NoneType _)
=> None;
}
public static class Option
{
public static Option<T> Of<T>(T value)
=> new Option<T>(value, value != null);
public static Option<TR> Map<T, TR>(
this Option<T> @this,
Func<T, TR> mapfunc
) =>
@this.IsSome
? Some(mapfunc(@this.Value))
: None;
public static Option<TR> Bind<T, TR>(
this Option<T> @this,
Func<T, Option<TR>> bindfunc
) =>
@this.IsSome
? bindfunc(@this.Value)
: None;
public static Option<Unit> ForEach<T>(
this Option<T> @this,
Action<T> action
) =>
Map(@this, ToFunc(action));
public static T GetOrElse<T>(
this Option<T> @this,
Func<T> fallback
) =>
@this.Match(
Some: value => value,
None: fallback
);
public static T GetOrElse<T>(
this Option<T> @this,
T @else
) =>
GetOrElse(@this, () => @else);
public static Option<T> Where<T>(
this Option<T> @this,
Func<T, bool> predicate
) =>
@this.IsSome && predicate(@this.Value) ? @this : None;
}
public struct NoneType {}
public static partial class Helpers
{
public static Option<T> Some<T>(T value) => Option.Of(value);
public static readonly NoneType None = new NoneType();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment