Version 1 of Summing a list

Updated 2001-12-15 12:57:48

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

 # 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