Search code examples
loopsrecursiontclprocedureproc

I'm trying to understand recursion in Tcl, but every time the recursion finishes it throws errors


I'm new to TCL, and trying to set up a simple recursion loop. The code I have works up until the recursion finishes, then it begins throwing errors. This is my code:

set testNum 0

proc raiseTest { a } {
    puts $a
    if { $a == 5 } {
        puts "Done!"
    } elseif { $a != 5 } {
        incr a
        puts "Going!"
        [raiseTest $a]
    } 
    
}

[ raiseTest $testNum ]

Once the proc reaches 5 and finishes it's last loop, I get hit with an invalid command name "" error followed by a ton of invoked from within errors and I have no idea why. Can someone help me out?


Solution

  • Two things

    1. You call a procedure without using the square brackets. You only use the square brackets when you need to capture the procedure's return value, which is not in this case
    2. The elseif {$a != 5} is redundant, you can replace it with just else

    To further discuss point #1, the line right after puts "Going!", which reads:

            [raiseTest $a]
    

    This line calls raiseTest $a, then because of the square brackets, capture the output of that call (an empty string because nothing was returned) and use that as the name of a proc and call it.

    Here is an example:

    proc foo {} {
        puts "foo"
        return "bar"
    }
    
    proc bar {} {
        puts "bar"
    }
    
    foo    ;# prints "foo"
    [foo]  ;# prints "foo", then "bar""
    

    That being said, the code should look like this, with the square brackets removed:

    proc raiseTest { a } {
        puts "a=$a"
        if { $a == 5 } {
            puts "Done!"
        } else {
            incr a
            puts "Going!"
            raiseTest $a
        }
    }
    
    set testNum 0
    raiseTest $testNum