1
0
mirror of https://github.com/DanilaFe/abacus synced 2024-06-26 04:36:24 -07:00
Abacus/core/src/main/java/org/nwapw/abacus/tree/NumberReducer.java

55 lines
2.0 KiB
Java
Raw Normal View History

package org.nwapw.abacus.tree;
import org.nwapw.abacus.Abacus;
2017-07-26 18:44:30 -07:00
import org.nwapw.abacus.function.Function;
import org.nwapw.abacus.number.NumberInterface;
/**
* A reducer implementation that turns a tree into a single number.
* This is not always guaranteed to work.
*/
public class NumberReducer implements Reducer<NumberInterface> {
/**
* The plugin manager from which to draw the functions.
*/
private Abacus abacus;
/**
* Creates a new number reducer.
2017-07-30 21:11:32 -07:00
*
* @param abacus the calculator instance.
*/
2017-07-30 21:11:32 -07:00
public NumberReducer(Abacus abacus) {
this.abacus = abacus;
}
@Override
public NumberInterface reduceNode(TreeNode node, Object... children) {
2017-07-30 21:11:32 -07:00
if (node instanceof NumberNode) {
return ((NumberNode) node).getNumber();
2017-08-02 10:41:52 -07:00
} else if (node instanceof BinaryNode) {
NumberInterface left = (NumberInterface) children[0];
NumberInterface right = (NumberInterface) children[1];
2017-08-02 10:41:52 -07:00
Function function = abacus.getPluginManager().operatorFor(((BinaryNode) node).getOperation()).getFunction();
2017-07-30 21:11:32 -07:00
if (function == null) return null;
2017-07-26 18:44:30 -07:00
return function.apply(left, right);
2017-08-02 10:41:52 -07:00
} else if (node instanceof UnaryNode) {
2017-07-28 11:14:45 -07:00
NumberInterface child = (NumberInterface) children[0];
2017-08-02 10:41:52 -07:00
Function functionn = abacus.getPluginManager().operatorFor(((UnaryNode) node).getOperation()).getFunction();
2017-07-30 21:11:32 -07:00
if (functionn == null) return null;
2017-07-28 11:14:45 -07:00
return functionn.apply(child);
2017-07-30 21:11:32 -07:00
} else if (node instanceof FunctionNode) {
2017-07-26 18:44:30 -07:00
NumberInterface[] convertedChildren = new NumberInterface[children.length];
2017-07-30 21:11:32 -07:00
for (int i = 0; i < convertedChildren.length; i++) {
2017-07-26 18:44:30 -07:00
convertedChildren[i] = (NumberInterface) children[i];
}
Function function = abacus.getPluginManager().functionFor(((FunctionNode) node).getFunction());
2017-07-30 21:11:32 -07:00
if (function == null) return null;
2017-07-26 18:44:30 -07:00
return function.apply(convertedChildren);
}
return null;
}
}