Created
June 2, 2013 14:41
-
-
Save potix2/5693738 to your computer and use it in GitHub Desktop.
memoized fibonacci
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Memoize1[-T, +R](f: T => R) extends (T => R) { | |
private[this] val memorized = scala.collection.mutable.Map.empty[T, R] | |
def apply(x: T):R = { | |
memorized.getOrElseUpdate(x, f(x)) | |
} | |
} | |
object Memoize1 { | |
def apply[T, R](f: T => R) = new Memoize1(f) | |
def Y[T,R](f: (T => R) => T => R) = { | |
lazy val yf: T => R = Memoize1(f(yf)(_)) | |
yf | |
} | |
} | |
def fib(n:Long):Long = n match { | |
case 0 | 1 => 1 | |
case _ => fib(n-2) + fib(n-1) | |
} | |
def fibCurry(f:Long => Long)(n:Long):Long = n match { | |
case 0 | 1 => 1 | |
case _ => f(n-2) + f(n-1) | |
} | |
lazy val fibMem = Memoize1.Y(fibCurry) | |
val fibBeginTime = System.nanoTime() | |
List.range[Long](2,40).map(fib) | |
println(System.nanoTime() - fibBeginTime) | |
val fibMemBeginTime = System.nanoTime() | |
List.range[Long](2,40).map(fibMem) | |
println(System.nanoTime() - fibMemBeginTime) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment