Skip to content

Instantly share code, notes, and snippets.

@arturaz
Created October 24, 2013 05:44
Show Gist options
  • Save arturaz/7131954 to your computer and use it in GitHub Desktop.
Save arturaz/7131954 to your computer and use it in GitHub Desktop.
Custom iteration in C# and Scala
public IEnumerator<Tuple2<T, Direction>> GetEnumerator() {
if (top != null)
yield return new Tuple2<T, Direction>(top, Direction.Top);
if (right != null)
yield return new Tuple2<T, Direction>(right, Direction.Right);
if (down != null)
yield return new Tuple2<T, Direction>(down, Direction.Down);
if (left != null)
yield return new Tuple2<T, Direction>(left, Direction.Left);
}
object Iterator {
def Accessors[A]: List[(Neighbourhood[A] => Option[A], Direction)] = List(
(_.top, Top), (_.right, Right), (_.down, Down), (_.left, Left)
)
}
class Iterator[A](neighbourhood: Neighbourhood[A])
extends scala.Iterator[(A, Neighbourhood.Direction)] {
private[this] var tail = Iterator.Accessors[A]
private[this] var _next: Option[(A, Direction)] = None
fetchNext()
def hasNext = _next.isDefined
def next() = {
val current = _next.get
fetchNext()
current
}
private[this] def fetchNext() {
tail match {
case (fetcher, direction) :: tl =>
tail = tl
_next = fetcher(neighbourhood).map { a => (a, direction) }
if (_next.isEmpty) fetchNext()
case Nil =>
_next = None
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment