serene-simple/src/main/java/serene/simple/ListNode.java

98 lines
2.3 KiB
Java

package serene.simple;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import static java.util.Arrays.asList;
public class ListNode<T extends Node> extends Node implements Iterable<T> {
public static final ListNode<?> EMPTY = new ListNode<>();
public final T first;
public final ListNode<T> rest;
public final int length;
public ListNode() {
this.first = null;
this.rest = null;
this.length = 0;
}
public ListNode(T f, ListNode<T> r) {
this.first = f;
this.rest = r;
this.length = r.length + 1;
}
@SafeVarargs
public static <T extends Node> ListNode<T> list(T... objs) {
return list(asList(objs));
}
public static <T extends Node> ListNode<T> list(List<T> objs) {
ListNode<T> l = (ListNode<T>) EMPTY;
for (int i = objs.size() - 1; i >= 0; i--) {
l = l.cons(objs.get(i));
}
return l;
}
public ListNode<T> cons(T node) {
return new ListNode<T>(node, this);
}
@Override
public Object eval(Scope scope) {
Function f = (Function) this.first.eval(scope);
List<Object> args = new ArrayList<Object>();
for (T node : this.rest) {
args.add(node.eval(scope));
}
return f.apply(args.toArray());
}
public T first() {
if (this != EMPTY) {
return this.first;
}
return null;
}
public ListNode<T> rest() {
if (this != EMPTY) {
return this.rest;
}
return (ListNode<T>) EMPTY;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private ListNode<T> l = ListNode.this;
@Override
public boolean hasNext() {
return this.l != EMPTY;
}
@Override
public T next() {
if (this.l == EMPTY) {
return null;
}
T first = this.l.first;
this.l = this.l.rest;
return first;
}
@Override
public void remove() {
throw new SereneException("Iterator is immutable");
}
};
}
}