Created
April 30, 2019 12:41
-
-
Save bblfish/ff3c55d7288f5608b7a6306c1fa6d4c6 to your computer and use it in GitHub Desktop.
Memoisation with state using Scala
This file contains 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
// Fixes memorization bug from code in | |
// http://blog.tmorris.net/posts/memoisation-with-state-using-scala/index.html | |
// Also adds little debugging tool to allow one to see how state evolves. | |
// returns the memorisation map, to help see that it has been altered. | |
object FibMemo1 { | |
type Memo = Map[BigInt, BigInt] | |
def fibmemo1(n: BigInt, debug: Boolean = false): (BigInt,Memo) = { | |
def fibmemoR(z: BigInt, memo: Memo): (BigInt, Memo) = | |
if(z <= 1) | |
(z, memo) | |
else memo get z match { | |
case None => { | |
val (r, memo0) = fibmemoR(z - 1, memo) | |
val (s, memo1) = fibmemoR(z - 2, memo0) | |
val res = r+s | |
if (debug) println(z+"->"+res) | |
(res, memo1 + Pair(z,res)) //<- the | |
} | |
case Some(v) => (v, memo) | |
} | |
fibmemoR(n, Map()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment