3
votes

I try to write a very simple program in TCL using list.

Below is the list

list { 1 2 3 4 5 6 1.5 7 }

Below is my code

set sum 0
for {set i 0} {$i < [llength $list]} {incr i} {
    incr sum [lindex $list $i]
}

puts  $sum

On executing the above program I am getting the below error due to floating point value of 1.5 in the list

expected integer but got "1.5"
    (reading increment)
    invoked from within
"incr sum [lindex $list $i]"

I searched on internet and could not find anything relevant. Please advise how do I handle the floating point value?

3

3 Answers

3
votes

While using incr command, variable must have value that can be interpreted as a an integer. See tcl wiki. If variable is a non-integral real number, [incr] could not be used, but [set] could:

set sum 0
for {set i 0} {$i < [llength $list]} {incr i} {
    set sum [expr {$sum + [lindex $list $i]}]
}

puts  $sum
3
votes

Omsai's answer should solve your problem, but a cleaner solution is to use foreach:

set sum 0
foreach n $list {
    set sum [expr {$sum + $n}]
}
puts $sum

Summing up a list of numeric values can also be done with the ::tcl::mathop::+ command:

::tcl::mathop::+ {*}$list

This looks more complicated that it is. The + command isn't available in the regular namespace, so you need to specify where it comes from (the ::tcl::mathop namespace). The command expects to get each operand as a separate argument, so if they are in a list you need to expand that list using the {*} prefix.

foreach and the various mathop commands are documented here: foreach, mathop.

(Note: the 'Hoodiecrow' mentioned in the comments is me, I used that nick earlier.)

0
votes

Tcl gives an error if you will try

incr a 1.5

you have to change the logic.

clearly you want to add all the numbers in the list. and answers are easy and many. But i will give you the shortest way:

set l { 1 2 3 4 5 6 1.5 7 }
set sum [expr [join $l +]]

NO LOOPING REQUIRED.