|
| 1 | +package week6.kalaparser; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.StringJoiner; |
| 7 | + |
| 8 | +import static week6.kalaparser.KalaNode.*; |
| 9 | + |
| 10 | +public sealed interface KalaNode permits KalaIdent, KalaList, KalaNull { |
| 11 | + |
| 12 | + int sum(Map<String, Integer> env); |
| 13 | + |
| 14 | + static KalaNode mkNull() { |
| 15 | + return new KalaNull(); |
| 16 | + } |
| 17 | + |
| 18 | + static KalaNode mkIdent(String name) { |
| 19 | + return new KalaIdent(name); |
| 20 | + } |
| 21 | + |
| 22 | + static KalaNode mkList(List<KalaNode> args) { |
| 23 | + return new KalaList(args); |
| 24 | + } |
| 25 | + |
| 26 | + static KalaNode mkList(KalaNode... args) { |
| 27 | + return mkList(Arrays.asList(args)); |
| 28 | + } |
| 29 | + |
| 30 | + |
| 31 | + // Siit edasi on siis lahendus ette antud, et selle peale mitte jälle liiga palju aega kulutada. |
| 32 | + // Nende peidetud "sisemiste" klasside asemel võid kodutöös teha täiesti eraldi avalikud klassid! |
| 33 | + |
| 34 | + record KalaIdent(String name) implements KalaNode { |
| 35 | + |
| 36 | + @Override |
| 37 | + public String toString() { |
| 38 | + return name; |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public int sum(Map<String, Integer> env) { |
| 43 | + throw new UnsupportedOperationException(); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + record KalaList(List<KalaNode> args) implements KalaNode { |
| 48 | + |
| 49 | + @Override |
| 50 | + public String toString() { |
| 51 | + StringJoiner joiner = new StringJoiner(", ", "(", ")"); |
| 52 | + for (KalaNode arg : args) joiner.add(arg.toString()); |
| 53 | + return joiner.toString(); |
| 54 | + } |
| 55 | + |
| 56 | + @Override |
| 57 | + public int sum(Map<String, Integer> env) { |
| 58 | + return args.stream().mapToInt(n -> n.sum(env)).sum(); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + record KalaNull() implements KalaNode { |
| 63 | + |
| 64 | + @Override |
| 65 | + public String toString() { |
| 66 | + return "NULL"; |
| 67 | + } |
| 68 | + |
| 69 | + @Override |
| 70 | + public int sum(Map<String, Integer> env) { |
| 71 | + return 0; |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments