Skip to content

Instantly share code, notes, and snippets.

@grignaak
Created May 25, 2011 06:45
Show Gist options
  • Save grignaak/990465 to your computer and use it in GitHub Desktop.
Save grignaak/990465 to your computer and use it in GitHub Desktop.
Ceylon vs Java iterators--implementation
// Ceylon
shared class PredicatedIterator<out X>(Iterator<X> delegate, Boolean where(X x))
satisfies Iterator<X> {
variable local current = delegate;
while (current.head exists && !where(current.head)) {
current := current.tail;
}
local actual = current;
shared actual X? head {
return actual.head;
}
shared actual Iterator<X> tail {
return PredicatedIterator(actual.tail, where);
}
}
public static class PredicatedCursor<T> implements Cursor<T> {
public interface Predicate<T> {
boolean apply(T element);
}
private final Predicate<? super T> predicate;
private final Cursor<T> delegate;
public PredicatedCursor(Cursor<T> delegate, Predicate<? super T> predicate) {
Cursor<T> current = delegate;
while (!delegate.isEmpty()) {
if (predicate.apply(delegate.head())) {
break;
}
current = delegate.tail();
}
this.delegate = current;
this.predicate = predicate;
}
public boolean isEmpty() {
return delegate.isEmpty();
}
public T head() {
return delegate.head();
}
public Cursor<T> tail() {
return new PredicatedCursor<T>(delegate, predicate);
}
}
//Java
public class PredicatedIterator<X> implements Iterator<X> {
public interface Predicate<X> {
boolean apply(X x);
}
private final Iterator<X> delegate;
private final Predicate<X> predicate;
private enum State { Ready, NotReady, Done, Failed };
private State state = State.NotReady;
private X current;
public PredicatedIterator(Iterator<X> delegate, Predicate<X> predicate) {
this.delegate = delegate;
this.predicate = predicate;
}
public boolean hasNext() {
switch(state) {
case Ready: return true;
case NotReady:
state = State.Failed;
while (delegate.hasNext()) {
current = delegate.next();
if (predicate.apply(current)) {
state = State.Ready;
return true;
}
}
state = State.Done;
return false;
default:
return false;
}
}
public X next() {
if (!hasNext())
throw new NoSuchElementException();
state = State.NotReady;
return current;
}
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment