Created
October 24, 2013 05:44
-
-
Save arturaz/7131954 to your computer and use it in GitHub Desktop.
Custom iteration in C# and Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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