Skip to content

Instantly share code, notes, and snippets.

@cem2ran
Created September 6, 2015 20:47
Show Gist options
  • Save cem2ran/0e46744122e5fa4ea216 to your computer and use it in GitHub Desktop.
Save cem2ran/0e46744122e5fa4ea216 to your computer and use it in GitHub Desktop.

Revisions

  1. cem2ran created this gist Sep 6, 2015.
    16 changes: 16 additions & 0 deletions unfold.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    def unfold[A,S](initial: S)(generateNext: S => Option[(A, S)]): Stream[A] =
    generateNext(initial) match {
    case Some((first, next)) => cons(first, unfold(next)(generateNext))
    case None => empty
    }

    val fibs =
    unfold((0,1)) {
    case (f0, f1) => Some((f0, (f1, f0+f1)))
    }

    def from(n: Int) =
    unfold(n)(n => Some(n, n+1))

    def constant[A](a: A) =
    unfold(a)(_ => Some((a, a)))