transcendental-lisp/eval/MINUS.java

61 lines
1.8 KiB
Java

/*
* Name: Mike Cifelli
* Course: CIS 443 - Programming Languages
* Assignment: Lisp Interpreter 1
*/
package eval;
import parser.*;
/**
* <code>MINUS</code> represents the '-' function in Lisp.
*/
public class MINUS extends LispFunction {
public SExpression call(Cons argList) {
// make sure we have received at least one argument
if (argList.nullp()) {
Cons originalSExpr = new Cons(new Symbol("-"), argList);
throw new RuntimeException("too few arguments given to -: " +
originalSExpr);
}
SExpression argFirst = argList.getCar();
Cons argRest = (Cons) argList.getCdr();
// make sure that the first argument is a number
if (argFirst.numberp()) {
LispNumber num1 = (LispNumber) argFirst;
if (argRest.nullp()) {
// there is only one argument, so return the additive
// inverse of the number
return new LispNumber(- num1.getValue());
}
SExpression argSecond = argRest.getCar();
// make sure that the next argument is a number as well
if (argSecond.numberp()) {
LispNumber num2 = (LispNumber) argSecond;
LispNumber difference = new LispNumber(num1.getValue() -
num2.getValue());
SExpression argCddr = argRest.getCdr();
if (argCddr.consp()) {
return call(new Cons(difference, argCddr));
}
return difference;
}
throw new RuntimeException("-: " + argSecond + " is not a number");
}
throw new RuntimeException("-: " + argFirst + " is not a number");
}
}