Skip to content

Instantly share code, notes, and snippets.

@tpolecat
Last active December 11, 2015 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpolecat/4646639 to your computer and use it in GitHub Desktop.
Save tpolecat/4646639 to your computer and use it in GitHub Desktop.
def unfold[A](a: A)(f: A => Option[A]): Stream[A] =
f(a).map(a => a #:: unfold(a)(f)).getOrElse(Stream.empty)
def hailstone(i: Int) = i #:: unfold(i) { n =>
if (n == 1) None else Some(if (n % 2 == 0) n / 2 else n * 3 + 1)
}
def main(args: Array[String]) {
println(hailstone(27).toList)
val (n, len) = (1 to 100000).map(n => (n, hailstone(n).length)).maxBy(_._2)
println("value=" + n + " len=" + len)
}
@qu1j0t3
Copy link

qu1j0t3 commented Jan 27, 2013

I would only put

n #:: {
on the following line, it's easily missed up there, but crucial

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