2017-07-25 21:57:14 -07:00
|
|
|
package org.nwapw.abacus.function;
|
|
|
|
|
|
|
|
import org.nwapw.abacus.number.NaiveNumber;
|
|
|
|
import org.nwapw.abacus.number.NumberInterface;
|
2017-07-24 13:44:38 -07:00
|
|
|
|
2017-07-24 14:26:09 -07:00
|
|
|
import java.util.HashMap;
|
|
|
|
|
2017-07-25 22:47:48 -07:00
|
|
|
/**
|
|
|
|
* A function that operates on one or more
|
|
|
|
* inputs and returns a single number.
|
|
|
|
*/
|
2017-07-24 13:44:38 -07:00
|
|
|
public abstract class Function {
|
|
|
|
|
2017-07-25 22:47:48 -07:00
|
|
|
/**
|
|
|
|
* A map to correctly promote different number implementations to each other.
|
|
|
|
*/
|
2017-07-25 13:58:09 -07:00
|
|
|
private static final HashMap<Class<? extends NumberInterface>, Integer> priorityMap =
|
|
|
|
new HashMap<Class<? extends NumberInterface>, Integer>() {{
|
2017-07-24 14:26:09 -07:00
|
|
|
put(NaiveNumber.class, 0);
|
|
|
|
}};
|
|
|
|
|
2017-07-25 22:47:48 -07:00
|
|
|
/**
|
|
|
|
* Checks whether the given params will work for the given function.
|
|
|
|
* @param params the given params
|
|
|
|
* @return true if the params can be used with this function.
|
|
|
|
*/
|
2017-07-25 13:58:09 -07:00
|
|
|
protected abstract boolean matchesParams(NumberInterface[] params);
|
2017-07-25 22:47:48 -07:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal apply implementation, which already receives appropriately promoted
|
|
|
|
* parameters that have bee run through matchesParams
|
|
|
|
* @param params the promoted parameters.
|
|
|
|
* @return the return value of the function.
|
|
|
|
*/
|
2017-07-25 13:58:09 -07:00
|
|
|
protected abstract NumberInterface applyInternal(NumberInterface[] params);
|
2017-07-24 13:44:38 -07:00
|
|
|
|
2017-07-25 22:47:48 -07:00
|
|
|
/**
|
|
|
|
* Function to check, promote arguments and run the function.
|
|
|
|
* @param params the raw input parameters.
|
|
|
|
* @return the return value of the function, or null if an error occurred.
|
|
|
|
*/
|
2017-07-25 13:58:09 -07:00
|
|
|
public NumberInterface apply(NumberInterface...params) {
|
2017-07-24 14:03:55 -07:00
|
|
|
if(!matchesParams(params)) return null;
|
2017-07-24 13:44:38 -07:00
|
|
|
return applyInternal(params);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|