by ghosty141 · 5y ago · 0 comments
C# with monads would be great.
public readonly struct Option<T>
{
public static readonly Option<T> NONE = new Option<T>();
//
public T Value { get; }
public bool HasValue { get; }
public Option(T value)
{
Value = value;
HasValue = value is { };
}
public Option<TR> Select<TR>(Func<T, TR> selector) => HasValue ? new Option<TR>(selector(Value)) : Option<TR>.NONE;
public Option<TR> SelectMany<TR>(Func<T, Option<TR>> selector) => HasValue ? selector(Value) : Option<TR>.NONE;
public T OrElse(T defValue = default) => HasValue ? Value : defValue;
}
You can of course add more utility functions besides these, eventually as extension methods, but it's a starting point.If you just need some ready-made monads, language-ext is the way to go: https://github.com/louthy/language-ext
We tried to bring some functional ideas into our Unity3D codebase with help of these resources, it's hard but doable.