transcendental-lisp/src/function/builtin/math/DIVIDE.java

37 lines
1.0 KiB
Java

package function.builtin.math;
import java.math.BigInteger;
import function.*;
import sexpression.*;
@FunctionNames({ "/" })
public class DIVIDE extends LispFunction {
private ArgumentValidator argumentValidator;
private MathFunction mathFunction;
public DIVIDE(String name) {
this.argumentValidator = new ArgumentValidator(name);
this.argumentValidator.setMinimumNumberOfArguments(1);
this.argumentValidator.setEveryArgumentExpectedType(LispNumber.class);
this.mathFunction = new MathFunction(this::getReciprocal, this::divide);
}
@Override
public LispNumber call(Cons argumentList) {
argumentValidator.validate(argumentList);
return mathFunction.callTailRecursive(argumentList);
}
private LispNumber getReciprocal(LispNumber number) {
return new LispNumber(BigInteger.ONE.divide(number.getValue()));
}
private LispNumber divide(LispNumber number1, LispNumber number2) {
return new LispNumber(number1.getValue().divide(number2.getValue()));
}
}