Version 1 of overproc

Updated 2007-12-06 17:39:06 by ro

Sly: Example of overloading proc by arguments count

  proc overproc {n p b} {
      # define dispatcher
      uplevel [list proc $n {args} [string map [list %N $n] {
          uplevel [list "%N with [llength $args] args"] $args
      }]]
      # define the function itself
      uplevel [list proc "$n with [llength $p] args" $p $b]
  }

Let's check it:

  overproc X {} {
      puts ABC
  }
  overproc X {a} {
      puts "xyz $a"
  }
  overproc X {a b} {
      puts "qwe $a $b"
  }
  X
  X 5
  X q w

Output:

  ABC
  xyz 5
  qwe q w

TODO: Work correctly with "args" list


ro 2007-12-06 : Interesting. Small, simple, and clear. Everytime overproc is used it redefines the dispatcher. You mention working correctly with 'args'. But what would it do with args? Would it send it to X {}, X {a}, or X {a b} ? It's not clear what 'working correctly with args' entails. I like it as is. Any further reworking of the code should be seperate, you would lose the simplicity and clarity. You used string map to substitute within {}'s, I usually use format. Nice work :)


Category Example