Avinash Kumar
Avinash Kumar

Reputation: 777

How to write tcl proc for numbers

I want to create a tcl proc/ command like
[1] should return 1
[2] should return 2
.
.
[18999] should return 18999

How i should write one proc to handle all the number commands

Upvotes: 1

Views: 141

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137577

This is very much not recommended! Also, you can't really make a single command to do all of this. However, the easiest method is to update the unknown procedure to create the commands you need on demand. Patching unknown needs a little care.

proc unknown args [concat {
    if {[llength $args] == 1 && [string is entier -strict [lindex $args 0]]} {
        set TheNumber [lindex $args 0]
        proc ::$TheNumber {} [list return $TheNumber]
        return $TheNumber
        # The semicolon on the next line is required because of the [concat]
    };
} [info body unknown]]

This will make trivial procedures on demand as long as their names look exactly like (full, extended) integers. (Supporting floats as well isn't too hard; it'd just be a matter of writing a slightly more complex test that also uses string is double.)

But be aware that unknown command handling is a slow way to do this; it's the mechanism that Tcl invokes immediately before it would otherwise have to throw an error because a command doesn't exist. We could have made it just return the value directly without creating the procedure, but then every time you called this you'd have the overhead of the unsuccessful search; making the procedures speeds things up.

Not using numbers as commands at all will speed your code up even more.

Upvotes: 3

Related Questions