summaryrefslogtreecommitdiff
path: root/dice-lang/src/main/java/bjc/dicelang/ast/ArithmeticCollapser.java
diff options
context:
space:
mode:
authorbculkin2442 <bjculkin@mix.wvu.edu>2016-04-17 15:02:01 -0400
committerbculkin2442 <bjculkin@mix.wvu.edu>2016-04-17 15:02:01 -0400
commit4fcefd106eb23295592e9cc23a0c5d63a28f9e76 (patch)
treee262854fc899c1bba65a4029bd9a500291f77e9e /dice-lang/src/main/java/bjc/dicelang/ast/ArithmeticCollapser.java
parent9a5aac3995cd92afbab0a4b29d42e61078ea0bb0 (diff)
Code maintenance and changes
Diffstat (limited to 'dice-lang/src/main/java/bjc/dicelang/ast/ArithmeticCollapser.java')
-rw-r--r--dice-lang/src/main/java/bjc/dicelang/ast/ArithmeticCollapser.java64
1 files changed, 64 insertions, 0 deletions
diff --git a/dice-lang/src/main/java/bjc/dicelang/ast/ArithmeticCollapser.java b/dice-lang/src/main/java/bjc/dicelang/ast/ArithmeticCollapser.java
new file mode 100644
index 0000000..5ad0a0f
--- /dev/null
+++ b/dice-lang/src/main/java/bjc/dicelang/ast/ArithmeticCollapser.java
@@ -0,0 +1,64 @@
+package bjc.dicelang.ast;
+
+import java.util.function.BinaryOperator;
+
+import bjc.dicelang.ast.nodes.IDiceASTNode;
+import bjc.dicelang.ast.nodes.OperatorDiceNode;
+import bjc.utils.data.IPair;
+import bjc.utils.data.Pair;
+import bjc.utils.funcdata.IFunctionalList;
+import bjc.utils.funcdata.ITree;
+import bjc.utils.funcdata.Tree;
+
+/**
+ * Responsible for collapsing arithmetic operators
+ *
+ * @author ben
+ *
+ */
+final class ArithmeticCollapser
+ implements IOperatorCollapser {
+ private OperatorDiceNode type;
+
+ private BinaryOperator<Integer> valueOp;
+
+ public ArithmeticCollapser(OperatorDiceNode type,
+ BinaryOperator<Integer> valueOp) {
+ this.type = type;
+ this.valueOp = valueOp;
+ }
+
+ @Override
+ public IPair<Integer, ITree<IDiceASTNode>> apply(
+ IFunctionalList<IPair<Integer, ITree<IDiceASTNode>>> nodes) {
+ IPair<Integer, ITree<IDiceASTNode>> initState =
+ new Pair<>(0, new Tree<>(type));
+
+ BinaryOperator<IPair<Integer, ITree<IDiceASTNode>>> reducer =
+ (accumulatedState, currentState) -> {
+ return reduceStates(accumulatedState,
+ currentState);
+ };
+
+ return nodes.reduceAux(initState, reducer, (state) -> state);
+ }
+
+ private IPair<Integer, ITree<IDiceASTNode>> reduceStates(
+ IPair<Integer, ITree<IDiceASTNode>> accumulatedState,
+ IPair<Integer, ITree<IDiceASTNode>> currentState) {
+ return accumulatedState
+ .bind((accumulatedValue, accumulatedTree) -> {
+ return currentState
+ .bind((currentValue, currentTree) -> {
+ accumulatedTree.addChild(currentTree);
+
+ Integer combinedValue =
+ valueOp.apply(accumulatedValue,
+ currentValue);
+
+ return new Pair<>(combinedValue,
+ accumulatedTree);
+ });
+ });
+ }
+} \ No newline at end of file