Calculate the sum over a container
From CodeCodex
| Image:Lightbulb.png Related content: |
| <DPL>
category=Math shownamespace=false </DPL> |
This code demonstrates how to calculate the sum of a container (most often an array or similar structure).
Contents |
[edit] See also
[edit] Implementations
[edit] Algol 68
The following function computes the sum of the elements of the array passed to it. The type of the array elements is called NUM, which can be defined as any suitable integer or real type.
MODE NUM = INT; # type of array element #
PROC sum = ([] NUM a) NUM :
BEGIN
NUM result := 0;
FOR i FROM LWB a TO UPB a DO
result +:= a[i]
OD;
result
END
For instance, the call
sum((3, 4, 5, 6))
returns 18.
[edit] Assembly
INT_MAX = 2147483647.
sum proc mov ecx,DWORD PTR [esp] add esp,4 xor eax,eax sum_loop1: add eax,DWORD PTR [esp] add esp,4 cmp DWORD PTR [esp],2147483647 jne sum_loop1 mov DWORD PTR [esp],ecx ret sum endp
[edit] C
int total( int numbers[], int size ) {
int sum = 0, i;
for ( i = 0 ; i < size ; i++ )
{
sum += numbers[i];
}
return sum;
}
[edit] C++
#include<numeric> sum = std::accumulate(coll.begin(),coll.end(),0);
[edit] Common Lisp
(reduce #'+ list) (reduce #'+ list :initial-value 0) ; improved version that also works with empty lists
Another way:
(apply #'+ list)
[edit] Excel
=SUM([cells])
[edit] F#
Seq.sum container
[edit] Haskell
sum container
[edit] Java
import java.util.*;
public class Total {
public static int total(int... values) {
int total = 0;
for (int i : values) total += i;
return total;
}
public static void main(String[] args) {
System.out.println("Total: %d: ", total(1,2,4,40));
}
}
[edit] OCaml
Summing is a special case of folding the addition operator starting with zero:
# let sum = List.fold_left ( + ) 0;; val sum : int list -> int = <fun>
For example:
# sum [1; 2; 4; 40];; - : int = 47
[edit] Perl
use List::Util qw(sum); sum @arr; sum 0, @arr; # improved version that also works with empty arrays
[edit] Python
A function that sums the values in a sequence is built into python, its name is 'sum'.
assert sum([1,2,3]) == 6
[edit] Ruby
class Array
def sum
inject { |s, v| s += v }
end
end
Or more concisely,
class Array
def sum
reduce(:+)
end
end
[edit] Scheme
(apply + list)
[edit] Zsh
zsum() {
local -a array
array=(1 2 3 4 5)
(( sum=${(j:+:)array} ))
return sum
}

