Version 4 of Summing a list

Updated 2010-06-10 16:14:18 by lars_h

Purpose: example of code to apply aritmethic sum operation to all elements of a list.

As of Tcl 8.5, one preferably uses the tcl::mathop::+ command and {*}:

  proc ladd {l} {::tcl::mathop::+ {*}$l}

Before that, other techniques were necessary...


 # Pass ladd a list and receive back a single value which is a total of
 # all the elements.  WARNING: assumes all elements are integer.
 proc ladd {l} {
        set total 0
        foreach nxt $l {
                incr total $nxt
        }
        return $total
 }

Do you think it would be harmful to students to see

    proc ladd l {
        if {![llength $l]} {return 0}
        return [expr [join $l +]]
    }

?


Harmful? Probably not. If it is faster, that would be fine. Now you can add doubles as well, but the overflow warning still applies ... Use of Mpexpr or some other extended math package is required to get around the innate limitations based on Tcl's implicit use of C numeric types. (The comments above also used to warn about not preventing overflow, but overflow from adding numbers isn't much of an issue in Tcl 8.5+, either.)


You can get even more functional and elegant if you append a dummy "+0", so an empty list causes no problems (and needs not to be tested):

    proc ladd L {expr [join $L +]+0} ;# RS

See also: Sample math programs - Arts and crafts of Tcl-Tk programming


Category Mathematics