-1

I am currently trying to understand the implementation details of the following memoizing procedure as shown in several variants in the Tcl wiki:

proc memoize {} {
    global memo
    set cmd [info level -1]
    if {[info level] > 2 && [lindex [info level -2] 0] eq "memoize"} return
    if {![info exists memo($cmd)]} {set memo($cmd) [eval $cmd]}
    return -code return $memo($cmd)
}

What is common to all of them is (to my understanding) that they compare the first word of the grandparent command (lindex [info level -2] 0) with literally the name of this memoizing procedure (in this case, "memoize").

Would there be any downside of changing this to comparing the grandparent command with this command, in other words, changing [lindex [info level -2] 0] eq "memoize" to [info level -2] eq [info level 0]?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

1

There's no appreciable downside except if you go round renaming commands mid-way, and that would just be very fragile indeed (so don't do that). Ultimately, the code is trying to detect where we have this:

foo ab cd ef                 <--- A
   memoize                   <--- B
      foo ab cd ef           <--- C
         memoize             <--- D

When it spots that stack configuration, it returns so that D does nothing, C returns the actual computed value, B caches that value, and A can then return it in the future without having to compute it. It's all rather complicated and hacky; I much prefer to just make functions know about caching of stuff properly.

It's also fragile in several other key ways, such as the memoized function being unable to use upvar or make recursive calls to itself. Some of the other options on that wiki page don't have that weakness. The recursive calls problem is probably best addressed (if you're not going to tackle it by using a different overall memoization strategy) through checking not the first word of the result of info level -2, but rather whether the whole pattern described is present (i.e., whether info level -1 is the same as info level -3 as well, and whether there is an info level -3 to be had at all).

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215