2019-12-12 00:17:41 +00:00
|
|
|
package serene.simple;
|
|
|
|
|
|
|
|
import java.util.function.Function;
|
|
|
|
|
|
|
|
public class FnSpecialForm extends SpecialForm {
|
2019-12-16 23:02:07 +00:00
|
|
|
public FnSpecialForm(ListNode<Node> paramsAndBody) {
|
2019-12-12 00:17:41 +00:00
|
|
|
super(paramsAndBody);
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public Object eval(final Scope parentScope) {
|
2019-12-14 02:42:25 +00:00
|
|
|
final ListNode<Node> formalParams = (ListNode<Node>) this.node.rest().first();
|
|
|
|
final ListNode<Node> body = this.node.rest().rest();
|
|
|
|
|
|
|
|
return new Function<Object, Object>() {
|
2019-12-12 00:17:41 +00:00
|
|
|
@Override
|
2019-12-14 02:42:25 +00:00
|
|
|
public Object apply(Object arg) {
|
|
|
|
Object args[] = {arg};
|
|
|
|
return this.apply(args);
|
|
|
|
}
|
|
|
|
|
2019-12-12 00:17:41 +00:00
|
|
|
public Object apply(Object... args) {
|
|
|
|
Scope scope = new Scope(parentScope);
|
2019-12-14 02:42:25 +00:00
|
|
|
if (args.length != formalParams.length) {
|
2019-12-12 00:17:41 +00:00
|
|
|
throw new RuntimeException(String.format("Wrong number of arguments. Expected: %s, Got: %s.",
|
2019-12-14 02:42:25 +00:00
|
|
|
formalParams.length,
|
2019-12-12 00:17:41 +00:00
|
|
|
args.length));
|
|
|
|
}
|
|
|
|
// Map parameter values to formal parameter names
|
|
|
|
int i = 0;
|
|
|
|
for (Node param : formalParams) {
|
|
|
|
SymbolNode paramSymbol = (SymbolNode) param;
|
2019-12-14 02:42:25 +00:00
|
|
|
scope.insertSymbol(paramSymbol.name, args[i]);
|
2019-12-12 00:17:41 +00:00
|
|
|
i++;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Evaluate body
|
|
|
|
Object output = null;
|
|
|
|
for (Node node : body) {
|
|
|
|
output = node.eval(scope);
|
|
|
|
}
|
|
|
|
return output;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|