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.*;
|
2016-12-15 15:33:48 -05:00
|
|
|
import sexpression.*;
|
2016-12-07 16:38:26 -05:00
|
|
|
|
|
|
|
public class APPLY extends LispFunction {
|
|
|
|
|
2016-12-22 10:32:48 -05:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2016-12-22 10:32:48 -05:00
|
|
|
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) {
|
2016-12-22 10:32:48 -05:00
|
|
|
argumentValidator.validate(argList);
|
2016-12-07 16:38:26 -05:00
|
|
|
|
|
|
|
Cons cdr = (Cons) argList.getCdr();
|
2016-12-22 10:32:48 -05:00
|
|
|
SExpression functionName = argList.getCar();
|
|
|
|
SExpression argumentList = cdr.getCar();
|
2016-12-07 16:38:26 -05:00
|
|
|
|
2016-12-22 10:32:48 -05:00
|
|
|
if (argumentList.listp()) {
|
|
|
|
LispFunction function = EVAL.lookupFunction(functionName.toString());
|
2016-12-07 16:38:26 -05:00
|
|
|
|
|
|
|
if (function == null) {
|
2016-12-22 10:32:48 -05:00
|
|
|
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 {
|
2016-12-22 10:32:48 -05:00
|
|
|
throw new RuntimeException("undefined function " + functionName);
|
2016-12-07 16:38:26 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-22 10:32:48 -05:00
|
|
|
return function.call((Cons) argumentList);
|
2016-12-07 16:38:26 -05:00
|
|
|
}
|
|
|
|
|
2016-12-22 10:32:48 -05:00
|
|
|
throw new RuntimeException("APPLY: " + argumentList + " is not a list");
|
2016-12-07 16:38:26 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|