Created
November 1, 2012 20:41
-
-
Save ashee/3996385 to your computer and use it in GitHub Desktop.
scala equivalent of haskell's cycle
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
// cycle will lazily cycle through values from the seq argument | |
def cycle[T](seq: Seq[T]) = Stream.continually(seq).flatten | |
scala> val c = cycle(List(1, 2, 3)) | |
scala> c take 10 force | |
res24: scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 1, 2, 3, 1, 2, 3, 1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like this, it's very neat on half a line. There's one danger lurking though.
When you try to cycle over an empty sequence, you'll melt your cpu. Just try
cycle(Nil) take 10 force
with your version of cycle.I would suggest wrapping the Stream.continually... in a block and guard it with an assertion first