fork download
  1. import java.util.Iterator;
  2.  
  3. enum Unit {
  4. Value;
  5. }
  6.  
  7. interface F0<A> {
  8. public A _();
  9. }
  10.  
  11. abstract class F1<A, B> {
  12. public abstract B _(A a);
  13. }
  14.  
  15. abstract class F2<A, B, C> {
  16. public abstract C _(A a, B b);
  17. }
  18.  
  19. abstract class Maybe<A> {
  20. public static <A> Maybe<A> unit(A value) {
  21. return Just.of(value);
  22. }
  23.  
  24. public abstract <B> Maybe<B> map(F1<A, B> f);
  25. public abstract <B> Maybe<B> flatMap(F1<A, Maybe<B>> f);
  26. public abstract A getOrElse(F0<A> alt);
  27. public abstract Maybe<A> orElse(Maybe<A> alt);
  28. public abstract <B> B fold(F1<A, B> f, F0<B> g);
  29. public abstract Maybe<A> filter(F1<A, Boolean> pred);
  30. }
  31.  
  32. class Just<A> extends Maybe<A> {
  33. private final A value;
  34.  
  35. private Just(A value) {
  36. this.value = value;
  37. }
  38.  
  39. public static <A> Maybe<A> of(A value) {
  40. return new Just<A>(value);
  41. }
  42.  
  43. public <B> Maybe<B> map(F1<A, B> f) {
  44. return new Just<B>(f._(value));
  45. }
  46.  
  47. public <B> Maybe<B> flatMap(F1<A, Maybe<B>> f) {
  48. return f._(value);
  49. }
  50.  
  51. public A getOrElse(F0<A> alt) {
  52. return value;
  53. }
  54.  
  55. public Maybe<A> orElse(Maybe<A> alt) {
  56. return this;
  57. }
  58.  
  59. public <B> B fold(F1<A, B> f, F0<B> g) {
  60. return f._(value);
  61. }
  62.  
  63. public Maybe<A> filter(F1<A, Boolean> pred) {
  64. if(pred._(value)) {
  65. return this;
  66. } else {
  67. return Nothing.<A>value();
  68. }
  69. }
  70.  
  71. @Override
  72. public String toString() {
  73. return String.format("Just(%s)", value);
  74. }
  75. }
  76.  
  77. class Nothing<A> extends Maybe<A> {
  78. private Nothing() {
  79. }
  80.  
  81. public static <A> Maybe<A> value() {
  82. return new Nothing<A>();
  83. }
  84.  
  85. public <B> Maybe<B> map(F1<A, B> f) {
  86. return new Nothing<B>();
  87. }
  88.  
  89. public <B> Maybe<B> flatMap(F1<A, Maybe<B>> f) {
  90. return new Nothing<B>();
  91. }
  92.  
  93. public A getOrElse(F0<A> alt) {
  94. return alt._();
  95. }
  96.  
  97. public Maybe<A> orElse(Maybe<A> alt) {
  98. return alt;
  99. }
  100.  
  101. public <B> B fold(F1<A, B> f, F0<B> g) {
  102. return g._();
  103. }
  104.  
  105. public Maybe<A> filter(F1<A, Boolean> pred) {
  106. return this;
  107. }
  108.  
  109. public String toString() {
  110. return "Nothing";
  111. }
  112. }
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout

Standard output is empty