transcendental-lisp/src/function/builtin/MULTIPLY.java

41 lines
1.2 KiB
Java
Raw Normal View History

2016-12-19 13:05:53 -05:00
package function.builtin;
2016-12-07 16:38:26 -05:00
import function.*;
import sexpression.*;
2016-12-07 16:38:26 -05:00
public class MULTIPLY extends LispFunction {
private ArgumentValidator argumentValidator;
public MULTIPLY() {
this.argumentValidator = new ArgumentValidator("*");
this.argumentValidator.setEveryArgumentExpectedType(LispNumber.class);
}
public LispNumber call(Cons argumentList) {
argumentValidator.validate(argumentList);
return callTailRecursive(new Cons(LispNumber.ONE, argumentList));
}
private LispNumber callTailRecursive(Cons argumentList) {
Cons remainingArguments = (Cons) argumentList.getCdr();
SExpression firstArgument = argumentList.getCar();
LispNumber number1 = (LispNumber) firstArgument;
2016-12-07 16:38:26 -05:00
if (remainingArguments.nullp())
return number1;
2016-12-07 16:38:26 -05:00
SExpression secondArgument = remainingArguments.getCar();
LispNumber number2 = (LispNumber) secondArgument;
LispNumber product = new LispNumber(number1.getValue().multiply(number2.getValue()));
SExpression remainingNumbers = remainingArguments.getCdr();
2016-12-07 16:38:26 -05:00
if (!remainingNumbers.consp())
return product;
2016-12-07 16:38:26 -05:00
return callTailRecursive(new Cons(product, remainingNumbers));
2016-12-07 16:38:26 -05:00
}
}