Advertisement
Guest User

Untitled

a guest
Apr 26th, 2015
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. //直和を表現しきれない点を気にしたら負け
  2. public interface IOption<out T> : IEnumerable<T>
  3. {
  4. bool HasValue { get; }//== this.Any()
  5. }
  6. sealed public class Some<T> : IOption<T>
  7. {
  8. private readonly T val;
  9. public bool HasValue { get { return true; } }
  10.  
  11. public Some(T v) {
  12. val = v;
  13. }
  14.  
  15. public IEnumerator<T> GetEnumerator() {
  16. yield return val;
  17. }
  18. IEnumerator IEnumerable.GetEnumerator() {
  19. return this.GetEnumerator();
  20. }
  21. }
  22. sealed public class None<T> : IOption<T>
  23. {
  24. public bool HasValue { get { return false; } }
  25.  
  26. public None() { }
  27.  
  28. public IEnumerator<T> GetEnumerator() {
  29. yield break;
  30. }
  31. IEnumerator IEnumerable.GetEnumerator() {
  32. return this.GetEnumerator();
  33. }
  34. }
  35.  
  36. static public class Option
  37. {
  38. static public Some<T> Some<T>(T v) {
  39. return new Some<T>(v);
  40. }
  41. static public None<T> None<T>() {
  42. return new None<T>();
  43. }
  44. static public IOption<T> Return<T>(T v) {
  45. if (v != null)
  46. return new Some<T>(v);
  47. else
  48. return new None<T>();
  49. }
  50. static public IOption<U> Bind<T, U>(this IOption<T> _, Func<T, IOption<U>> f) {
  51. return _.HasValue ?
  52. f(_.First()) :
  53. Option.None<U>();
  54. }
  55. static public IOption<T> ToOption<T>(this IEnumerable<T> _) {
  56. if (_.Any())
  57. return Option.Some<T>(_.First());
  58. else
  59. return Option.None<T>();
  60. }
  61. static public U Match<T, U>(this IOption<T> _, Func<T, U> Some, Func<U> None) {
  62. return _.HasValue ?
  63. Some(_.First()) :
  64. None();
  65. }
  66. static public void Match<T>(this IOption<T> _, Action<T> Some, Action None) {
  67. if (_.HasValue)
  68. Some(_.First());
  69. else
  70. None();
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement