Skip to content

Instantly share code, notes, and snippets.

@DiveInto
Last active December 22, 2015 04:39
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 DiveInto/6418637 to your computer and use it in GitHub Desktop.
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.
/**
* 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