Tcl Anonymous Functions

A Purely Theoretical Question of Tcl.

Following this question , I was thinking about what would be the best way to implement anonymous functions in Tcl.

The end result should allow the developer to pass the full proc as an argument to the proc run:

do_something $data {proc {} {input} { puts $input; }}; 

which will be similar to javascript

 do_something(data, function (input) { alert(input); }); 

Now, of course, this will not work OOTB. I was thinking of something like that:

 proc do_something {data anon_function} { anon_run $anon_function $data } proc anon_run {proc args} { set rand proc_[clock clicks]; set script [lreplace $proc 1 1 $rand]; uplevel 1 $script; uplevel 1 [concat $rand $args]; uplevel 1 rename $rand {}; //delete the created proc } 

It works. But I was hoping to get suggestions for a better template, then this, since it is not very elegant and does not really use the cool Tcl features. Basically I would like to get rid of the manual call of anon_run .

+7
tcl
source share
1 answer

In Tcl 8.5, you can use the apply command.

 proc do_something {data anon_function} { apply $anon_function $data } do_something $data {{input} { puts $input }} 

Of course, if you structure your callbacks as command prefixes (recommended!), You can do this:

 proc lambda {arguments body} { # We'll do this properly and include the optional namespace set ns [uplevel 1 namespace current] return [list ::apply [list $arguments $body $ns]] } proc do_something {data command} { {*}$command $data } do_something $data [lambda {input} { puts $input }] 

If you use 8.4 or earlier, you need code from the Tcler Wiki as a replacement, but keep in mind that these solutions are only semantically equivalent (at best); they are not equivalent to performance.

+11
source share

All Articles