1
votes

I'm a beginner at TCL and while trying to build the GCD algorithm I ran into some problems I'd like some help with:

how can I call a proc inside a proc recursively like so

proc Stein_GCD { { u  0 } { v  0 } } {
    if { $v == 0 } {
        puts "$u\t\t$v\t\t$v"
    }
    if { [expr { $v % 2 } && { $u % 2 } ] == 0 } {
        return [expr 2 * ${Stein_GCD 1 0} ]
    }
}  
set a [Stein_GCD 2 2 ]
puts $a

as you can see, I made the proc to evaluate GCD(the code does not make any sense because I'm trying to solve an example issue), and I'm trying to recursively call the proc again to continue evaluating(notice that I made an if statement that can understand the Stein_GCD 1 0 call, yet the tcl 8.6.6 online EDA emulator says:

can't read "Stein_GCD 1 0": no such variable
    while executing
"expr 2 * ${Stein_GCD 1 0} "
    (procedure "Stein_GCD" line 5)
    invoked from within
"Stein_GCD 2 2 "
    invoked from within
"set a [Stein_GCD 2 2 ]"
    (file "main.tcl" line 7)

Can you tell me how to efficiently recursively call a proc, and where was my mistake?
will gladly provide more info in the case I did a bad job at explaining.

1
Apart from everything else, as a matter of style you're better off writing if {!(($v % 2) && ($u % 2))} { for that internal if call; it's both more efficient and quite a bit clearer. And I'm guessing that you'll need to do more work to handle other cases of recursion… – Donal Fellows

1 Answers

3
votes

The error can't read "Stein_GCD 1 0": indicates that you are treating the data as a single string instead of separate arguments. The problem line:

 return [expr 2 * ${Stein_GCD 1 0} ]

is not written correctly. ${Stean_GCD 1 0} is not a variable. You should have:

 return [expr 2 * [Stein_GCD 1 0] ]

You want the result from Stein_GCD 1 0, so the brackets should be used.