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

49 lines
1.5 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
2016-12-19 13:05:53 -05:00
import function.*;
import sexpression.*;
2016-12-07 16:38:26 -05:00
public class APPLY extends LispFunction {
private static final int NUMBER_OF_ARGUMENTS = 2;
private ArgumentValidator argumentValidator;
2016-12-07 16:38:26 -05:00
public static SExpression apply(Cons argList) {
return new APPLY().call(argList);
}
public APPLY() {
this.argumentValidator = new ArgumentValidator("APPLY");
this.argumentValidator.setExactNumberOfArguments(NUMBER_OF_ARGUMENTS);
}
2016-12-07 16:38:26 -05:00
public SExpression call(Cons argList) {
argumentValidator.validate(argList);
2016-12-07 16:38:26 -05:00
Cons cdr = (Cons) argList.getCdr();
SExpression functionName = argList.getCar();
SExpression argumentList = cdr.getCar();
2016-12-07 16:38:26 -05:00
if (argumentList.listp()) {
LispFunction function = EVAL.lookupFunction(functionName.toString());
2016-12-07 16:38:26 -05:00
if (function == null) {
if (functionName.functionp()) {
function = ((LambdaExpression) functionName).getFunction();
} else if (LAMBDA.isLambdaExpression(functionName)) {
Cons lexpr = (Cons) functionName;
2016-12-07 16:38:26 -05:00
function = LAMBDA.createFunction(lexpr);
} else {
throw new RuntimeException("undefined function " + functionName);
2016-12-07 16:38:26 -05:00
}
}
return function.call((Cons) argumentList);
2016-12-07 16:38:26 -05:00
}
throw new RuntimeException("APPLY: " + argumentList + " is not a list");
2016-12-07 16:38:26 -05:00
}
}