From 76705ed92b8d06f8f43e22ee912a295339a2108d Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Wed, 26 Jul 2017 10:58:27 -0700 Subject: [PATCH] Implement the ability to reduce a tree to a single variable of a type. --- src/org/nwapw/abacus/tree/NumberNode.java | 5 +++++ src/org/nwapw/abacus/tree/OpNode.java | 9 +++++++++ src/org/nwapw/abacus/tree/Reducer.java | 17 +++++++++++++++++ src/org/nwapw/abacus/tree/TreeNode.java | 2 ++ 4 files changed, 33 insertions(+) create mode 100644 src/org/nwapw/abacus/tree/Reducer.java diff --git a/src/org/nwapw/abacus/tree/NumberNode.java b/src/org/nwapw/abacus/tree/NumberNode.java index 1ac4ea9..f88ef0a 100644 --- a/src/org/nwapw/abacus/tree/NumberNode.java +++ b/src/org/nwapw/abacus/tree/NumberNode.java @@ -44,4 +44,9 @@ public class NumberNode extends TreeNode { public NumberInterface getNumber() { return number; } + + @Override + public T reduce(Reducer reducer) { + return reducer.reduceNode(this); + } } diff --git a/src/org/nwapw/abacus/tree/OpNode.java b/src/org/nwapw/abacus/tree/OpNode.java index b338064..33ba805 100644 --- a/src/org/nwapw/abacus/tree/OpNode.java +++ b/src/org/nwapw/abacus/tree/OpNode.java @@ -18,6 +18,8 @@ public class OpNode extends TreeNode { */ private TreeNode right; + private OpNode() {} + /** * Creates a new operation node with the given operation * and no child nodes. @@ -79,4 +81,11 @@ public class OpNode extends TreeNode { public void setRight(TreeNode right) { this.right = right; } + + @Override + public T reduce(Reducer reducer) { + T leftReduce = left.reduce(reducer); + T rightReduce = right.reduce(reducer); + return reducer.reduceNode(this, leftReduce, rightReduce); + } } diff --git a/src/org/nwapw/abacus/tree/Reducer.java b/src/org/nwapw/abacus/tree/Reducer.java new file mode 100644 index 0000000..966478d --- /dev/null +++ b/src/org/nwapw/abacus/tree/Reducer.java @@ -0,0 +1,17 @@ +package org.nwapw.abacus.tree; + +/** + * Interface used to reduce a tree into a single value. + * @param the value to reduce into. + */ +public interface Reducer { + + /** + * Reduces the given tree into a single value of type T. + * @param node the node being passed in to be reduced. + * @param children the already-reduced children of this node. + * @return the resulting value from the reduce. + */ + public T reduceNode(TreeNode node, Object...children); + +} diff --git a/src/org/nwapw/abacus/tree/TreeNode.java b/src/org/nwapw/abacus/tree/TreeNode.java index d549621..58e98b3 100644 --- a/src/org/nwapw/abacus/tree/TreeNode.java +++ b/src/org/nwapw/abacus/tree/TreeNode.java @@ -137,4 +137,6 @@ public abstract class TreeNode { return fromStringRecursive(string, matches); } + public abstract T reduce(Reducer reducer); + }