Skip to content

Instantly share code, notes, and snippets.

@bblfish
Created April 30, 2019 12:41
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 bblfish/ff3c55d7288f5608b7a6306c1fa6d4c6 to your computer and use it in GitHub Desktop.
Save bblfish/ff3c55d7288f5608b7a6306c1fa6d4c6 to your computer and use it in GitHub Desktop.
Memoisation with state using Scala
// 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