Last active
August 29, 2015 14:26
-
-
Save andresmoschini/d5dfca8ac46ba3e4d8d5 to your computer and use it in GitHub Desktop.
Maybe Monad C# implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
namespace Utilities | |
{ | |
public static class Maybe | |
{ | |
public static Maybe<T> From<T>(T value) => new Maybe<T>(value); | |
public static Maybe<T> None<T>() => default(Maybe<T>); | |
} | |
public struct Maybe<T> : IEnumerable<T> | |
{ | |
readonly bool _hasValue; | |
public bool HasValue => _hasValue; | |
readonly T _value; | |
public T Value | |
{ | |
get | |
{ | |
if (!_hasValue) | |
{ | |
throw new InvalidOperationException(); | |
} | |
return _value; | |
} | |
} | |
internal Maybe(T value) | |
{ | |
_hasValue = !ReferenceEquals(value, null); | |
_value = value; | |
} | |
public static implicit operator Maybe<T>(T value) => new Maybe<T>(value); | |
public IEnumerator<T> GetEnumerator() | |
{ | |
if (_hasValue) | |
{ | |
yield return _value; | |
} | |
yield break; | |
} | |
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment