61 lines
1.8 KiB
Java
61 lines
1.8 KiB
Java
/*
|
|
* Name: Mike Cifelli
|
|
* Course: CIS 443 - Programming Languages
|
|
* Assignment: Lisp Interpreter 1
|
|
*/
|
|
|
|
package eval;
|
|
|
|
import parser.*;
|
|
|
|
/**
|
|
* <code>DIVIDE</code> represents the '/' function in Lisp.
|
|
*/
|
|
public class DIVIDE 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 multiplicative
|
|
// inverse of the number
|
|
return new LispNumber(1 / 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 quotient = new LispNumber(num1.getValue() /
|
|
num2.getValue());
|
|
SExpression argCddr = argRest.getCdr();
|
|
|
|
if (argCddr.consp()) {
|
|
return call(new Cons(quotient, argCddr));
|
|
}
|
|
|
|
return quotient;
|
|
}
|
|
|
|
throw new RuntimeException("/: " + argSecond + " is not a number");
|
|
}
|
|
|
|
throw new RuntimeException("/: " + argFirst + " is not a number");
|
|
}
|
|
|
|
}
|