Skip to content

Commit 0227fb0

Browse files
committed
5
1 parent 86e1eab commit 0227fb0

File tree

1 file changed

+52
-0
lines changed
  • java/src/main/java/v/o/i/d/monadsplain

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)