Last active
December 22, 2015 04:39
-
-
Save DiveInto/6418637 to your computer and use it in GitHub Desktop.
I'll speak generally, then. About recursive functions using a cache: they must return, in addition of the result, an upated cache.
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
/** | |
* https://class.coursera.org/progfun-002/forum/thread?thread_id=1175#comment-3124 | |
**/ | |
object Main extends App { | |
class MemoStringFunction[T](f: String => T, base: String) { | |
private lazy val v = f(base) | |
private lazy val ts = (for { | |
tx <- 'a' to 'z' | |
} yield (tx, new MemoStringFunction(f, base + tx))).toMap | |
private def get(x: String): T = x match { | |
case "" => v | |
case s => ts(s.head).get(s.tail) | |
} | |
def apply(x: String): T = get(x) | |
} | |
val f = new MemoStringFunction(s => { println("bork."); s.length }, "") | |
println(f("a")) | |
println(f("abcdef")) | |
println(f("a")) | |
println(f("abcdef")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment