self-modifying code

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:

Self-modifying code interferes with byte-compilation and can very easily introduce bugs, so it should be used with care. On the other hand, there are forms of radical language modification that simply wouldn't be possible without it!

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!
 %

Of course, this isn't restricted to rewriting the body of procedures:

  proc intgen {{i 0}} {
    proc intgen "{i [expr {$i+1}]}" [info body intgen]
    return $i
  }

RLE (2011-05-21) fixed intgen to work properly.