overproc

Larry Smith stacking?


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 :)


Sly:

2 ro: Thank you :)

For one proc name, the dispatcher will be the same every call. I wonder which is cheaper: to check whether the dispatcher exists or blindly to define it. Anyway, the latter is more good-looking. And procs are defined not so often for this to be an issue.

My idea about args:

 (1) overproc X {} { ... }
 (2) overproc X {a} { ... }
 (3) overproc X {a b args} { ... }
 (4) overproc X {a b c d e} { ... }
 (5) overproc X {a b c d e f args} { ... }

     X                 ; # (1) is called
     X 1               ; # (2) is called
     X 1 2             ; # (3) is called
     X 1 2 3           ; # (3) is called
     X 1 2 3 4         ; # (3) is called
     X 1 2 3 4 5       ; # (4) is called
     X 1 2 3 4 5 6     ; # (5) is called

Sure, this implementation will not be as cute and clear. I'd prefer to keep it simple by now.

Agree about format :)

2 Larry Smith: Indeed, this kind of overloading is not like stacking. As I understand, stacking is like next of XOTcl. It extends the functionality of existing functions. overproc doesn't. overproc can be easily emulated with stacking, though.

(shall we add our remarks at the bottom of the page?)

To be fair, I was thinking of another (minimalistic) implementation of an infix little language, operator overloading will take place there.


Category Example