|
| 1 | +package v.o.i.d.monadsplain; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.function.Function; |
| 5 | +import java.util.stream.Stream; |
| 6 | + |
| 7 | +public class Five { |
| 8 | + public static class IntegerWithHistory { |
| 9 | + public final Integer value; |
| 10 | + public final String[] history; |
| 11 | + |
| 12 | + public IntegerWithHistory(Integer value, String... history) { |
| 13 | + this.value = value; |
| 14 | + this.history = history; |
| 15 | + } |
| 16 | + |
| 17 | + public static IntegerWithHistory wrap(Integer i) { |
| 18 | + return new IntegerWithHistory(i); |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + public IntegerWithHistory calculate(IntegerWithHistory i, Function<Integer, IntegerWithHistory> operation) { |
| 23 | + final IntegerWithHistory a = operation.apply(i.value); |
| 24 | + return new IntegerWithHistory( |
| 25 | + a.value, |
| 26 | + join(i.history, join(i.history, a.history)) |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + public void run() { |
| 31 | + Function<Integer, IntegerWithHistory> addOne = i -> new IntegerWithHistory(i + 1, "addOne: " + i); |
| 32 | + Function<Integer, IntegerWithHistory> square = i -> new IntegerWithHistory(i * i, "square: " + i); |
| 33 | + IntegerWithHistory i = calculate( |
| 34 | + calculate(IntegerWithHistory.wrap(3), square), |
| 35 | + addOne); |
| 36 | + System.out.println(i.value); |
| 37 | + System.out.println(Arrays.toString(i.history)); |
| 38 | + } |
| 39 | + |
| 40 | + public static void main(String[] args) { |
| 41 | + new Three().run(); |
| 42 | + } |
| 43 | + |
| 44 | + private static String[] join(String[] array, String element) { |
| 45 | + return Stream.concat(Arrays.stream(array), Stream.of(element)).toArray(String[]::new); |
| 46 | + } |
| 47 | + |
| 48 | + private static String[] join(String[] array, String[] elements) { |
| 49 | + return Stream.concat(Arrays.stream(array), Stream.of(elements)).toArray(String[]::new); |
| 50 | + } |
| 51 | + |
| 52 | +} |
0 commit comments