RSS

================================================================================

Before Today

================================================================================

If I was crying
In the van, with my friend
It was for freedom
From myself and from the land

================================================================================

09/21/2010 23:18:13

Scala | collatz

def collatz(n: Int) = n match {
  case n if n % 2 == 0 => n / 2
  case n               => (3 * n) + 1
}

def nestWhileList[A](f: A => A, initial: A, p: A => Boolean) = {
  val result = Stream.iterate(initial)(f).takeWhile(p).toList
  result :+ f(result.last)
}

val cs = nestWhileList(collatz(_: Int), 200, (_: Int) != 1)

--------------------------------------------------------------------------------

 

================================================================================

Designed: Robert Boylan
Powered: Tumblr