Skip to content

Instantly share code, notes, and snippets.

@nlinker
Forked from aloiscochard/Stream.scala
Last active August 29, 2015 14:06
Show Gist options
  • Save nlinker/baa65dbfb0ae1f919a8a to your computer and use it in GitHub Desktop.
Save nlinker/baa65dbfb0ae1f919a8a to your computer and use it in GitHub Desktop.
import Stream._
/** A possibly finite stream that repeatedly applies a given function to a start value.
*
* @param start the start value of the stream
* @param f the function that's repeatedly applied
* @return the stream returning the possibly finite sequence of values `start, f(start), f(f(start)), ...`
*/
def iterate[A](f: A => A, a: A): Stream[A] = unfold((x: A) => Some((x, f(x))), a)
def unfold[A, B](start: B)(f: B => Option[Tuple2[A,B]]): Stream[A] = f(start) match {
case Some((elem, next)) => elem #:: unfold(next)(f)
case None => empty
}
// Could be integrated here -> https://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_9_1_final/src//library/scala/collection/immutable/Stream.scala#L647
@nlinker
Copy link
Author

nlinker commented Sep 20, 2014

missingfaktor commented on Nov 2, 2011

Why not just use Stream.iterate ?
scala> Stream.iterate(2)(2 *)
res29: scala.collection.immutable.Stream[Int] = Stream(2, ?)

scala> res29 take 10 toList
res30: List[Int] = List(2, 4, 8, 16, 32, 64, 128, 256, 512, 1024)
Owner
aloiscochard commented on Nov 2, 2011

@missingfaktor because Stream.iterate only support infinite sequence, with my version you can stop by returning None
missingfaktor commented on Nov 2, 2011

Oh, I see. It's more similar to unfold from Scalaz.
scala> 5.unfold [Stream, Int](x => if%28x < 100%29 Some%28x * 2, x + 1%29 else None)
res41: Stream[Int] = Stream(10, ?)

scala> res41.toList
res42: List[Int] = List(10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198)
Owner
aloiscochard commented on Nov 3, 2011

Ok, I'm reinventing scalaz here :-D ... Make sense, I had this idea while learning haskell!

But I still believe it should be in scala-core as presented here.

Thanks for pointing this out mate.
missingfaktor commented on Nov 3, 2011

Welcome, mate! Yes, I agree unfold is pretty basic, and deserves a place in the standard library.
Owner
aloiscochard commented on Nov 3, 2011

I've just added unfold implementation which could be integrated in std lib

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment