Functions have been done

This commit is contained in:
Sameer Rahmani 2019-12-18 14:02:04 +00:00
parent 730c9a91cb
commit 3e35e1fe8a
5 changed files with 22 additions and 18 deletions

View File

@ -1,2 +1,2 @@
repl:
gradle compileJava && rlwrap java -cp bin/main/ serene.simple.Main
gradle compileJava && rlwrap java -cp build/classes/java/main/ serene.simple.Main

View File

@ -14,12 +14,9 @@ public class FnSpecialForm extends SpecialForm {
return new Function<Object, Object>() {
@Override
public Object apply(Object arg) {
Object args[] = {arg};
return this.apply(args);
}
public Object apply(Object arguments) {
Object[] args = (Object[]) arguments;
public Object apply(Object... args) {
Scope scope = new Scope(parentScope);
if (args.length != formalParams.length) {
throw new RuntimeException(String.format("Wrong number of arguments. Expected: %s, Got: %s.",
@ -39,6 +36,7 @@ public class FnSpecialForm extends SpecialForm {
for (Node node : body) {
output = node.eval(scope);
}
return output;
}
};

View File

@ -44,16 +44,16 @@ public class ListNode<T extends Node> extends Node implements Iterable<T> {
@Override
public Object eval(Scope scope) {
Function f = (Function) this.first().eval(scope);
Function<Object, Object> f = (Function) this.first().eval(scope);
List<Object> args = new ArrayList<Object>();
for (T node : this.rest) {
for (T node : this.rest()) {
args.add(node.eval(scope));
}
return f.apply(args.toArray());
}
public T first() {
public T first() {
if (this != EMPTY) {
return this.first;
}

View File

@ -26,6 +26,7 @@ public class Main {
System.out.println("Serene 'simple' v0.1.0");
while(true) {
String inputData = console.readLine("serene-> ");
//String inputData = "(fn (x) x)";
if (inputData == null) break;
@ -34,6 +35,7 @@ public class Main {
try {
Object result = ListNode.EMPTY;
for (Node n : nodes) {
result = n.eval(rootScope);
}

View File

@ -76,7 +76,7 @@ public class Reader {
while (true) {
int ch = inputStream.read();
if(isWhiteSpace(ch) || ch == -1) {
if(isWhiteSpace(ch) || isClosingChar(ch) || ch == -1) {
inputStream.unread(ch);
break;
};
@ -100,16 +100,20 @@ public class Reader {
}
private static void skipWhiteSpaces(PushbackReader inputStream) throws IOException {
int ch = inputStream.read();
while (isWhiteSpace(ch)) {
ch = inputStream.read();
}
inputStream.unread(ch);
int ch = inputStream.read();
while (isWhiteSpace(ch)) {
ch = inputStream.read();
}
inputStream.unread(ch);
}
private static boolean isWhiteSpace(int ch) {
return (ch == ' ' || ch == '\t' ||
ch == '\f' || ch == '\r' ||
ch == '\n');
return (ch == ' ' || ch == '\t' || ch == '\f' || ch == '\r' || ch == '\n');
}
private static boolean isClosingChar(int ch) {
return (ch == ')' || ch == ']' ||
ch == '}');
}
}