Re: is possible to have a proc within a proc?



On May 29, 8:17 pm, chedderslam <chedders...@xxxxxxxxx> wrote:
I am working on a proc which calls itself recursively.  Is it possible
for a proc to have a proc within itself?  I am trying to group the
code together.

There are two concepts here: (1) recursivity and (2) local functions.
You should realize that they are really orthogonal. I'm sure you've
already seen a recursive proc in C (which lacks local functions), and
also local functions in Pascal which are not recursive. So why are you
mixing them here ?

Now, assuming it's local functions that you're after, the short answer
is No, Tcl doesn't have local procs.

The long answer is: Tcl on the other hand has powerful primitives
allowing you to limit the visibility of code or data. These are
namespaces and (new to 8.5) lambdas. A namespace (or simply a function
with a funny name) doesn't give you strict privacy, but may be
sufficient for your purpose. If you insist, a higher degree of
insulation can be reached with lambdas:

proc outer x {
set inner {u {incr u;expr {$u*$u}}}
...
apply $inner $x
...
}

I don't know exactly about the overhead induced by [apply], but the
execution of the lambda itself will not be slower than a regular
proc's starting from the second invocation, since the bytecode will be
cached with the literal. It only displaces compilation time from [proc
outer] time to first-runtime.

-Alex
.