-
-
Save yoeluk/ac6b9a5482463bf2ed34 to your computer and use it in GitHub Desktop.
This file contains 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
// immutable cycle | |
class Node[T]( val value: T, _next: => Node[T] ){ | |
lazy val next = _next | |
} | |
val cycle: Node[Int] = new Node( 1, new Node( 2, cycle ) ) | |
// prints List(1, 2, 1, 2, 1, 2, 1, 2, 1, 2) | |
println(cycle.iterator.take(10).map(_.value).toList) | |
implicit class NodeIterator[T](node: Node[T]){ | |
def iterator = new Iterator[Node[T]]{ | |
var current = node | |
def next = { | |
val previous = current | |
current = current.next | |
previous | |
} | |
val hasNext = true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment