Version 2 of self-modifying code

Updated 2011-05-21 14:25:48 by aspect

Self-modifying code is an unusual feature in programming languages, and not one I've seen so beautifully used anywhere else than in Tcl. There are several examples of self modifying procedures on this wiki:

Procedures that modify themselves in Tcl generally follow a pattern like this:

proc hibye {} {
  puts "Hello, world!"
  proc hibye {} {
    puts "Goodbye, world"
    rename repeat {}
  }
}
 % hibye
 Hello, world!
 % hibye
 Goodbye, world
 % hibye
 invalid command name "hibye"

It is easy to end up in Quoting hell when rewriting procedures. A pattern that seems to have become common is using string map in this fashion:

proc and_then {more} {
  puts "No more and then!"
  proc and_then {more} [string map [list @MORE@ $more @BODY@ [info body and_then]] {
    puts "and then @MORE@"
    @BODY@
  }]
}
 % and_then bacon
 No more and then!
 % and_then cheese
 and then bacon
 No more and then!
 % and_then cheese
 and then cheese
 and then bacon
 No more and then!
 %