Last active
August 29, 2015 14:11
-
-
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)
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
// 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