Guest User

Untitled

a guest
Jan 17th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. public class Maybe<T>
  2. {
  3. private readonly T value;
  4.  
  5. private Maybe(bool hasValue, T value) : this(hasValue) => this.value = value;
  6.  
  7. private Maybe(bool hasValue) => HasValue = hasValue;
  8.  
  9. public bool HasValue {get;}
  10.  
  11. public T Value => HasValue ? value : throw new InvalidOperationException();
  12.  
  13. public static Maybe<T> None {get;} = new Maybe<T>(false);
  14.  
  15. public static Maybe<T> Some(T value) => new Maybe<T>(true, value);
  16.  
  17. public Maybe<U> Bind<U>(Func<T, Maybe<U>> f) => HasValue ? f(value) : Maybe<U>.None;
  18. }
  19.  
  20. var client = Maybe<int>.Some(1)
  21. .Bind(orderId => GetOrder(orderId))
  22. .Bind(order => GetClient(order.ClientId));
  23. Console.WriteLine(client);
  24.  
  25. var client = Maybe<int>.Some(1)
  26. .Bind(orderId => GetOrderAsync(orderId))
  27. .Bind(order => GetClientAsync(order.ClientId));
  28. Console.WriteLine(client);
  29.  
  30. public Maybe<U> Bind<U>(Func<T, Task<Maybe<U>>> f)
  31. => HasValue ? f(value).Result : Maybe<U>.None;
  32.  
  33. public async Task<Maybe<U>> Bind<U>(Func<T, Task<Maybe<U>>> f)
  34. => HasValue ? await f(value) : Maybe<U>.None;
  35.  
  36. var asyncClient = await (await 2.ToMaybe()
  37. .Bind(orderId => GetOrderAsync(orderId)))
  38. .Bind(order => GetClientAsync(order.ClientId));
Add Comment
Please, Sign In to add comment