mirror of
https://github.com/DanilaFe/abacus
synced 2024-12-23 07:50:09 -08:00
Implement the ability to reduce a tree to a single variable of a type.
This commit is contained in:
parent
ce2373be8e
commit
76705ed92b
|
@ -44,4 +44,9 @@ public class NumberNode extends TreeNode {
|
|||
public NumberInterface getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T reduce(Reducer<T> reducer) {
|
||||
return reducer.reduceNode(this);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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> T reduce(Reducer<T> reducer) {
|
||||
T leftReduce = left.reduce(reducer);
|
||||
T rightReduce = right.reduce(reducer);
|
||||
return reducer.reduceNode(this, leftReduce, rightReduce);
|
||||
}
|
||||
}
|
||||
|
|
17
src/org/nwapw/abacus/tree/Reducer.java
Normal file
17
src/org/nwapw/abacus/tree/Reducer.java
Normal file
|
@ -0,0 +1,17 @@
|
|||
package org.nwapw.abacus.tree;
|
||||
|
||||
/**
|
||||
* Interface used to reduce a tree into a single value.
|
||||
* @param <T> the value to reduce into.
|
||||
*/
|
||||
public interface Reducer<T> {
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
}
|
|
@ -137,4 +137,6 @@ public abstract class TreeNode {
|
|||
return fromStringRecursive(string, matches);
|
||||
}
|
||||
|
||||
public abstract <T> T reduce(Reducer<T> reducer);
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user