Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Maybe<T>
- {
- private readonly T value;
- private Maybe(bool hasValue, T value) : this(hasValue) => this.value = value;
- private Maybe(bool hasValue) => HasValue = hasValue;
- public bool HasValue {get;}
- public T Value => HasValue ? value : throw new InvalidOperationException();
- public static Maybe<T> None {get;} = new Maybe<T>(false);
- public static Maybe<T> Some(T value) => new Maybe<T>(true, value);
- public Maybe<U> Bind<U>(Func<T, Maybe<U>> f) => HasValue ? f(value) : Maybe<U>.None;
- }
- var client = Maybe<int>.Some(1)
- .Bind(orderId => GetOrder(orderId))
- .Bind(order => GetClient(order.ClientId));
- Console.WriteLine(client);
- var client = Maybe<int>.Some(1)
- .Bind(orderId => GetOrderAsync(orderId))
- .Bind(order => GetClientAsync(order.ClientId));
- Console.WriteLine(client);
- public Maybe<U> Bind<U>(Func<T, Task<Maybe<U>>> f)
- => HasValue ? f(value).Result : Maybe<U>.None;
- public async Task<Maybe<U>> Bind<U>(Func<T, Task<Maybe<U>>> f)
- => HasValue ? await f(value) : Maybe<U>.None;
- var asyncClient = await (await 2.ToMaybe()
- .Bind(orderId => GetOrderAsync(orderId)))
- .Bind(order => GetClientAsync(order.ClientId));
Add Comment
Please, Sign In to add comment