Skip to content

Instantly share code, notes, and snippets.

@lanceon
Forked from xuwei-k/Main.scala
Last active August 29, 2015 14:10
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 lanceon/9fc46d2b0abf837aa182 to your computer and use it in GitHub Desktop.
Save lanceon/9fc46d2b0abf837aa182 to your computer and use it in GitHub Desktop.
scalaVersion := "2.9.1"
libraryDependencies ++= Seq(
"org.scalaz" %% "scalaz-core" % "6.0.3"
)
initialCommands in console := "import scalaz._;import Scalaz._"
scalacOptions ++= Seq(
"-deprecation"
)
package scalaz_memo_example
import scala.util.control.Exception.allCatch
import scalaz._
import Scalaz._
object Main{
def timer[T](f : => T):T = {
val start = System.currentTimeMillis
val r = f
println("\n" + (System.currentTimeMillis - start))
r
}
val ZERO = BigInt(0)
val ONE = BigInt(1)
def fib(n:Int):BigInt = {
require(n >= 0)
def f(x:BigInt):BigInt = x match {
case ZERO => x
case ONE => x
case _ => f(x-1) + f(x-2)
}
f(n)
}
val bigIntMemo = arrayMemo[BigInt](100)
val memorizedFib = bigIntMemo(fib)
def main(args:Array[String]){
val n = allCatch.opt{args.head.toInt}.getOrElse(35)
timer{ print( memorizedFib(n) ) }
timer{ print( memorizedFib(n) ) }
timer{ print( memorizedFib(n) ) }
}
}
[info] Running scalaz_memo_example.Main
9227465
3814
9227465
0
9227465
0
[success] Total time: 15 s, completed Oct 22, 2011 2:12:15 PM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment