Function overloading in TCL

Are there any packages or any specific way to support function or procedure overloading in TCL?

This is my scenario. I need to write a generic procedure that takes two or three files, in which I may or may not have a third file (File3)

                 proc fun { File1 File2 File3 }
                    {
                    }

                 proc fun { File1 File2 }
                    {
                    }

      

+3


source to share


4 answers


There is no override in tcl. The second declaration will simply replace the first. But you are handling it with one procedure. There are at least two ways:

1) Provide the last argument with its default value. It will then be optional when calling the function.

proc fun { file1 file2 {file3 ""} } {
  if {$file3 != ""} {
    # the fun was called with 3rd argument
  }
}

      



2) Use a special argument args

that will contain all arguments as a list. Then analyze the number of arguments passed.

proc fun { args } {
  if {[llength $args] == 3} {
    # the fun was called with 3rd argument
  }
}

      

+8


source


Tcl does not actually support procedure overloading, which makes sense when you consider that it actually has no types. This is all a string that can, depending on the value, be interpreted as other types (int, list, etc.).

If you can describe what you are trying to accomplish (why you think you need to overload), we could make a recommendation on how to accomplish it.



Given the change in your question, there are several different ways to do this. GrAnd showed 2 of them. The third, and I'm a fan, is to use the information about how the command was called:

proc fun { File1 File2 {File3 ""}} {     ;# file3 has a default
    if {[llength [info level 0]] == 3} { ;# we were called with 2 arguments
                                         ;# (proc name is included in [info level 0])
        # do what you need to do if called as [fun 1 2]
    } else {                             ;# called with 3 arguments
        # do what you need to do if called as [fun 1 2 3]
    }
}

      

+4


source


Here's an example of a puts hack, using the namespace to hide the puts and ::

to access the inline:

namespace eval newNameSpace {
  proc puts {arg} {
    set tx "ADDED:: $arg"
    ::puts $tx 
  }
  puts 102 
}

      

+2


source


Another way you can do it:

proc example {
    -file1:required
    -file1:required
    {-file3 ""}
} {
    if {$file3 ne ""} {
            #Do something ...
    }
}

      

when you call proc

example -fiel1 info -file2 info2

      

+1


source







All Articles