Skip to content

Instantly share code, notes, and snippets.

@cvogt
Last active August 29, 2015 14:11
Show Gist options
  • Save cvogt/b86aff8ac51f49a574cc to your computer and use it in GitHub Desktop.
Save cvogt/b86aff8ac51f49a574cc to your computer and use it in GitHub Desktop.
Immutable cycles (as seen in "Case classes a la carte with shapeless, now!" at scalax2014 by @milessabin)
// 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