I am reading "Exploring Expect: A TCL-Based Toolkit ... " by Don Libes.
An end of chapter question asked to "Write a procedure to reverse a string. If you wrote an iterative solution, now write a recursive solution or vice versa."
Reading up to this point in time, I decided to try the following:
set list {a b c d e f g}
for {set index [expr [llength $list]-1]} {$index>=0} {incr $index - 1} {
for {set i [expr [llength $list]-1]} {$i>=0} {incr $i - 1} {
puts [lindex $list $index]
}
}
But I get the following error:
Error(s), warning(s):
wrong # args: should be "incr varName ?increment?"
while executing
"incr $i - 1"
("for" body line 3)
invoked from within
"for {set index [expr [llength $list]-1]} {$index>=0} {incr $index - 1} {
for {set i [expr [llength $list]-1]} {$i>=0} {incr $i - 1} {
puts [lind..."
(file "source_file.tcl" line 4)
g
I see that I am not incrimenting the "index" variable correctly though I am unsure as to why. Also, is this approach recursive or iterative?
Any advice will be greatly appreciated.
________SOLUTION____________________________________
Based on the solution/approach provided by @glenn the correct code is as follows:
set list {a b c d e f g}
for {set i [expr {[llength $list]-1}]} {$i>=0} {incr i -1} {
puts [lindex $list $i]
}
Many other examples are shown by his post below.
First thing, you are passing 3 arguments to incr: $index
, -
and 1
. As the error message indicates, incr takes a maximum of 2 arguments. Specify "minus 1" as -1
with no spaces.
Take careful note of the error message:
wrong # args: should be "incr varName ?increment?"
Note how it says varName
-- when you use $index
you are passing the variable's value not the name. Remove the $
for {set i [expr {[llength $list]-1}]} {$i>=0} {incr i -1} {
# .................................................. ^ ^^
# varname increment
Note the braces around the argument to expr: that's a good habit to get into.