Version 3 of Summing a list

Updated 2010-06-10 14:17:36 by LVwikignoming

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...

Note that the new ladd allows non-integer values - and overflow appears to be pushed off for a while.

% ladd [lrepeat 1000 1111111111111111]
1111111111111111000
% ladd [lrepeat 1000000 1111111111111111]
1111111111111111000000
% ladd [lrepeat 1000000000 1111111111111111]
Not enough memory to allocate list

Abort(coredump)

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

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


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.


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

Category Mathematics