See ArraySum for problem description and context.
(List now alphabeticized for your convenience)

AplLanguage:

AwkLanguage:

CeePlusPlus:

CsharpLanguage: The most direct and efficient way to go is this:

CommonLisp:*This won't work with CL arrays of rank > 1, which seems to be the point of this page*
I'm not sure where the requirement can be read that it has to work
on arrays of rank > 1. Are the other examples for other languages
with multi-dimensional arrays taking care of it? What do you think?
(The CL example that is given later on this page for example
might give errors if the array has a fill-pointer.)
For those who prefer something a bit more amusing:

CoqAssistant?:

DeeCee To consume the whole main stack, here is a macro "S":

ForthLanguage:

HaskellLanguage: The HaskellLanguage equivalent of reduce are the foldl and foldr higher order functions. They both have the same behaviour when used with the + operator (note that parenthesising an operator turns it into a function):

IokeLanguage:

J (JayLanguage):

JavaLanguage: Proper software engineers should not use one-liners. So, here is a Java version:

JavaScript: As a PrototypeBasedLanguage, it is most convenient to add this method to the base Array object via its prototype:

KayLanguage:

LogoLanguage:

MatLab: Assuming x is an array of numbers:

NemerleLanguage: (a list, rather than an array, but close enough)

OberonLanguage:

ObjectiveCaml:**not** polymorphic, hence the two versions.

PerlLanguage:

PhpLanguage:

PythonLanguage:

R ( ArrLanguage )

RubyLanguage:*or*
*one of ruby's nice features is that you can extend classes, including the system classes, without changing their source code. The above could be:*
*And, as always, there's a better way to do it*
*And then there's the slightly more general expression, which returns nil as its "0", but works for all types of lists*

**ScalaLanguage**

SchemeLanguage: At last, a chance to show off the**do** construct of the SchemeLanguage:
*Doesn't Scheme have a fold/reduce/collect/whatever function?*
[He's kidding. I hope. Presumably springboarding off the above Java joke. ]
*Actually, while R5RS does not define any of them, one of the SchemeRequestsForImplementation (SRFI-1, List Library) has a full complement of fold and reduce functions. Thus, in an implementation that supports SRFI-7 and SRFI-1, one could write,*
*Mind you, these are *list* reduction functions, and so technically do not fit the problem description. That's OK, though, since writing a fold-vector function would be fairly easy:*
*(note that this code has only been cursorily tested and may have bugs). Of course, one could use *(vector->list)* and then apply the list *(fold)*, but that doesn't exactly match the problem. Adapting this to work with homogeneous-numeric vectors (SRFI 4) or multidimensional arrays (SRFI 25) is left as an exercise. - JayOsako*
You can sum lists in Scheme by
*I see ***one** argument there.
Then look again. The elements of *lst* are being turned into arguments to *+*. If there are more elements in the list than your implementation's limit on args passed to a procedure, then you lose.
*It is exactly ***one** argument. The list is not expanded into its elements. However, the task was to give a sum function for **arrays**. Since there are no native arrays in Scheme (just like C), the function does not deal with arrays. As for vectors, you either have to resort to the function given above or use (vector->list array) in the second version with some overhead.
That's certainly how it is in CommonLisp. In CommonLisp you'd use REDUCE: (defun sum-sequence (s) (reduce #'+ s :initial-value 0)), which works for both lists and vectors.
Common lisp actually has a (multivariate) array type, so in that case you could do something like

SmalltalkLanguage:*Except that #detectSum: isn't part of redbook Smalltalk. Try this instead:*

**SmlLanguage**
Lines starting with a dash contain the code. Other lines have been printed by the compiler.

SqlLanguage (assuming your "array" is a column of a table):

SwiftLanguage:

TclLanguage: (In tcl a 'list' is the equivalent of a numerically indexed array)*or - if using Tcl's associative 'arrays' *

VisualBasicNine: The most direct and efficient way to go is this:

VisualBasicForApplications:

ExBase

Contributors: Various AnonymousDonors, TomAnderson, EarleMartin

This is the type of problem in which CollectionOrientedProgramming languages are clearly better geared for.

Also see CounterInManyProgrammingLanguages, DotProductInManyProgrammingLanguages, HelloWorldInManyProgrammingLanguages, WardNumberInManyProgrammingLanguages, BetterForLoopConstruct

CategoryInManyProgrammingLanguages

AplLanguage:

X <- +/A

AwkLanguage:

function array_sum(a, i,s) { for (i in a) s+=a[i] return s }

CeePlusPlus:

template<class Container> typename Container::value_type containerSum(const Container& container) { return std::accumulate( container.begin(), container.end(), Container::value_type(0)); }or

template<class T> vector<T>::value_type ArraySum(vector<T> &array) { T retVal; int cntr; for(cntr = 0 ; cntr < array.size() ; cntr++) { cntr==0?retVal =array[0]:retVal += array[cntr]; } return retVal; }Will work if T has an '=' and a '+' operator. see GrokBranching (before modifying above algorithm) or you could use a higher level library such as Blitz++, BlitzPlusPlus

sum( A );Two more modern C++11 versions:

template<typename T> auto Sum(T input) -> typename T::value_type { typename T::value_type result{}; for(auto x : input) result += x; return result; } template<typename T> auto Sum(std::initializer_list<T> input) -> T { auto j = begin(input); auto result = *j++; for(; j != end(input); ++j) result += *j; return result; }The former works with any container that supports begin() and end(), the latter works with bare initializer lists and uses a slightly more "correct" loop:

auto data = std::vector<int>{1, 2, 3, 4, 5}; auto data = std::list<int>{1, 2, 3, 4, 5}; auto data = std::array<int, 5>{{1, 2, 3, 4, 5}}; cout << Sum(data) << endl; cout << Sum({1, 2, 3, 4, 5}) << endl;The following will work (C++11) for arrays, initializer_lists, valarrays, and any container that exposes appropriate begin() and end() methods. It may be made to work for other types by specializing std::begin and std::end for those types.

std::vector<int> data{1, 2, 3, 4, 5}; int sum = 0; std::for_each(std::begin(data), std::end(data), [&](int item){ sum += item; });

CsharpLanguage: The most direct and efficient way to go is this:

int[] numbers = { 1, 2, 3, 4, 5 }; int sum = 0; foreach (int n in numbers) sum += n;This can also be written using the generic Aggregate operator defined by LINQ over any sequence of values.

int[] numbers = { 1, 2, 3, 4, 5 }; int sum = numbers.Aggregate((a, b) => a + b);LINQ also predefines the Min, Max, Average, and Sum aggregates, which means you can just write it like this:

int[] numbers = { 1, 2, 3, 4, 5 }; int sum = numbers.Sum();-- DonBox

CommonLisp:

(defun sum-sequence (s) (reduce #'+ s)) (sum-sequence '(1 2 3)) -> 6

(defun sum-sequence (seq) (loop for x across seq summing x))Loop is just amusing.

CoqAssistant?:

Require Import List. Require Import Arith. Definition arraysum a := fold_left plus a O. Fixpoint running_sum a l {struct l} := %l decreases with every recursive call a :: match l with | nil => nil | cons b l' => running_sum (plus a b) l' end. Check sum. sum : list nat -> nat Eval compute in sum (1::2::3::nil). = 6 : nat Check running_sum. running_sum : nat -> list nat -> list nat Eval compute in running_sum 0 (1::2::3::nil). = 0::1::3::6::nil : list nat

DeeCee To consume the whole main stack, here is a macro "S":

[+z1<S] sSTo use it:

1 2 3 4 5 lSxTo consume a given number of arguments (and leave registers as they were):

[ Sn [+ln1-dsn1<m] Sm lmx LmXLn*1=X ] sS [I will not be eaten] 5 4 3 2 1 5 lSx f15[I will not be eaten]

ForthLanguage:

: table create , does> cell+ ; : tableSize cell- @ ; : tableSum 0 over dup tableSize cells + rot ( sum extent table ) ?do I @ + cell +loop ; 4 table aTable 1 , 2 , 3 , 4 , aTable tableSum . \ 10

HaskellLanguage: The HaskellLanguage equivalent of reduce are the foldl and foldr higher order functions. They both have the same behaviour when used with the + operator (note that parenthesising an operator turns it into a function):

arraysum = foldl (+) 0This idiomatic use of currying is equivalent to:

arraysum a = foldl (+) 0 aAnd it's good practice to explicitly declare the function type, although the compiler can infer the type from it's use:

arraysum :: Num a => [a] -> aTo produce the running sum, we use a counterpart to foldl: scanl, which produces each step of "folding" the operator in.

runningsum ns = tail $ scanl (+) 0 nsGiving a type of:

runningsum :: (Num a) => [a] -> [a]Even simpler: arraysum = sum

IokeLanguage:

a inject(+)Or, equivalently:

a fold(+)or:

a reduce(+)These three are actually identical (they're names for identical macros). They work on any type which understands "+", including strings.

J (JayLanguage):

+/ANote that this works on arrays of any rank, producing an array of one less than that rank. Thus, the sum reduces the array by the last axis. This behavior is more formal in J (JayLanguage) than in AplLanguage (see below). By the way, the reducing operation doesn't have to be plus - it can be any "binary" (we call them dyadic) function - such as multiply. Just replace the "+" with the appropriate primitive. For even more fun,

+/\AProduces the RUNNING sums.

JavaLanguage: Proper software engineers should not use one-liners. So, here is a Java version:

public interface Operator { public Object apply( Object lhs, Object rhs ) ; } public class CollectOperator implements Operator { private Operator op; public CollectOperation( Operator op ) { this.op = op ; } public Object apply( Collection coll, Object start ) { Object accumulator = start ; Iterator it = coll.iterator() ; while (it.hasNext()) { Object obj = it.next() ; accumulator = op.apply( accumulator, obj ) ; } return accumulator ; } } public class IntArrayList extends AbstractList { private int[] arr ; public IntArrayList( int[] arr ) { this.arr = arr ; } public int size() { return arr.length ; } public Object get( int index ) { int i = arr[index] ; return new Integer( i ) ; } } public class AddOperator implements Operator { public Object apply( Object lhs, Object rhs ) { int l = ((Integer)lhs).intValue() ; int r = ((Integer)rhs).intValue() ; int sum = l + r ; return new Integer( sum ) ; } } public int arraySum ( int[] arr ) { List l = new IntArrayList( arr ) ; Operator add = new AddOperator() ; Operator collectAdd = new CollectOperator( add ) ; Object sum = collectAdd.apply( l ) ; return ((Integer)sum).intValue() ; }As you can see, Java is a far superior language to all others! -- TomAnderson Hehehe... a serious case of YouArentGonnaNeedIt-itis with BigDesignUpFront complications. Here's a simple version:

public static int sum( int[] a ) { int sum = 0; for( int i = 0; i < a.length; i++ ) sum += a[i]; return sum; } /** * Java 5.0. */ // Returns the sum of the elements of array a // (blatantly plagarized from http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html ) public static int sum(int[] a) { int result = 0; for (int n : a) result += n; return result; }

JavaScript: As a PrototypeBasedLanguage, it is most convenient to add this method to the base Array object via its prototype:

Array.prototype.sum = function() { var n = 0; for (var i=0; i<this.length; i++) n += this[i]; return n; } assert( [1,2,3,4,5].sum() == 15 )See also BlocksInJavaScript for another implementation using an inject() factor. Since ECMA5.1 (JavaScript 1.8), reduce is available. (source: http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Example:_Sum_up_all_values_within_an_array )

var total = [0, 1, 2, 3].reduce(function(a, b) { return a + b; }); // total == 6

KayLanguage:

x:+/a

LogoLanguage:

show reduce "sum [1 2 3 4 5] ; quirk: won't work on the empty list show (sum 1 2 3 4 5) show apply "sum [1 2 3 4 5]

MatLab: Assuming x is an array of numbers:

my_sum_scalar = sum(x(:));will return a single value, the total of all the numbers in the entire array.

my_sum_vector = sum(x);can take a 2D array of numbers and will return the sum "vector", a 1D array of the sum of each column of the array. (It also does something useful for 3D and higher-dimensional arrays -- the same as J (JayLanguage)).

NemerleLanguage: (a list, rather than an array, but close enough)

using Nemerle.Collections.List; module Sum { Main(): void { def l = [1, 2, 3, 4]; def sum = FoldLeft(l, 0, _+_); System.Console.WriteLine(sum); //prints "10" } }

OberonLanguage:

MODULE Example; PROCEDURE ArraySum*(r: ARRAY OF INTEGER); VAR sum: INTEGER; i: INTEGER; BEGIN sum := 0; FOR i := 0 TO LEN(r) - 1 DO sum := sum + r[i] END; END ArraySum; END Example.

ObjectiveCaml:

let int_sum = List.fold_left (+) 0;; (* for integers *) let float_sum = List.fold_left (+.) 0.;; (* for floats *)Note that the plus operator in OCaml is

PerlLanguage:

my $sum = 0; # initialize to 0 to give the correct result for an empty array $sum += $_ foreach @array;Or a subroutine, if that's too long to type each time:

sub sum { my $s = 0; $s += $_ for @_; $s } print sum(1, 2, 3, 4, 5);The function has already been written:

use List::Util qw(sum); print sum(0, @array), "\n"; # need the 0 to give the correct result for an empty array

PhpLanguage:

$sum = array_sum($array);or:

$sum = 0; foreach ($array as $item) { $sum += $item; }

PythonLanguage:

arraysum = sum(array)If you want to write it out yourself you could use reduce:# As we say in Brooklyn, "Terse is cherce."

import operator arraysum = reduce( operator.add, array, 0 )Or you could just use a loop:

total = 0 for value in array: total += valueIf you are summing floats in Python 2.6+, you should use math.fsum(), which avoids loss of precision:

import math arraysum = math.fsum(array)

R ( ArrLanguage )

sum(anArray)

RubyLanguage:

def sumArray(a) sum = 0 a.each {|x| sum = sum + x } return sum end

module ArraySum def sum() sum = 0 self.each {|x| sum = sum + x } return sum end end a = Array.[](1, 2, 3) a.extend ArraySum puts a.sum

class Array def sum s = 0; each {|x| s = s + x}; s end end [1, 2, 3, 4].sum => 10

def sumArray(a) a.inject(0) { |sum, value| sum + value } end

def sum a a.inject { |sum, i| sum + i } end

def sum(a: Int*) = (0 /: a) (_ + _)Lest you conclude that ScalaLanguage is an incomprehensible language, let me point out that "/:" is right-associative synonym for "foldLeft" and "(_ + _)" is shorthand for ((i, j) => i + j) so the above could be equivalently written:

def sum(a: Int*) = (a foldLeft 0) ((i, j) => i + j)Or with more Java-like syntax:

def sum(a: Int*) = a.foldLeft(0) {(i, j) => i + j }Scala 2.8 now has it built in to all collections so the above function is simply:

def sum(a: Int*) = a sum

SchemeLanguage: At last, a chance to show off the

(define (vector-sum vec) (do ((i 0 (+ i 1)) (sum 0 (+ sum (vector-ref vec i)))) ((= i (vector-length vec)) sum))) (vector-sum '#(1 2 3))

(program (requires srfi-1)) (fold + 0 '(1 2 3 4 5))

(define (fold-right-vector op initial vec) (let ((endpoint (- (vector-length vec) 1))) (if (> 0 endpoint) initial (begin (op initial (let accumulate ((count 0)) (if (>= count endpoint) (vector-ref vec count) (op (vector-ref vec count) (accumulate (add1 count)))))))))) (define (vector-sum vec) (fold-right-vector + 0 vec)) (vector-sum #(1 2 3 4 5))

(define (list-sum lst) (apply + lst))Aren't Scheme implementations allowed to have a smallish upper limit on how many arguments you can pass to a procedure? If so, that solution might not work for long lists.

(defun sum-array (a) (loop for n below (array-total-size a) summing (row-major-aref a n)))

SmalltalkLanguage:

myArray := #(1 2 3 4 5). sum := myArray detectSum: [ :n | n + 0 ].

Array>>sum^self inject: 0 into: [:each :sum | each + sum]

Standard ML of New Jersey v110.57 [built: Fri Feb 10 21:37:49 2006] - val intArraySum = Array.foldl op+ 0 ; [autoloading] [library $SMLNJ-BASIS/basis.cm is stable] [autoloading done] val intArraySum = fn : int array -> int - val realArraySum = Array.foldl op+ 0.0 ; val realArraySum = fn : real array -> real - intArraySum (Array.tabulate (10, fn i => i)) ; val it = 45 : int - realArraySum (Array.tabulate (10, real)) ; val it = 45.0 : real

SqlLanguage (assuming your "array" is a column of a table):

select sum(x) from a

SwiftLanguage:

a.reduce(0) { $0 + $1 }

TclLanguage: (In tcl a 'list' is the equivalent of a numerically indexed array)

if {[llength $arr]} {expr [join $arr +]} {expr 0}

set sum 0 foreach {nm val} [array get arrName] { incr sum $val }

VisualBasicNine: The most direct and efficient way to go is this:

Dim numbers%() = { 1, 2, 3, 4, 5 } Dim sum = 0 For Each n In numbers sum = sum + n NextThis can also be written using the generic Aggregate operator defined by LINQ over any sequence of values.

Dim numbers%() = { 1, 2, 3, 4, 5 } Dim sum = numbers.Aggregate(Function(a, b) a + b)LINQ also predefines the Min, Max, Average, and Sum aggregates, which means you can just write it like this:

Dim numbers%() = { 1, 2, 3, 4, 5 } Dim sum = numbers.Sum()-- DonBox

VisualBasicForApplications:

WorksheetFunction.sum(anArray)

ExBase

* Populate an array. DIMENSION aSumArray[10] FOR x = 1 TO 10 aSumArray(x) = x ENDFOR * Sum its contents. LOCAL oursum oursum = 0 FOR x = 1 TO ALEN(aSumArray) oursum = oursum + aSumArray(x) ENDFOR-- KenDibble

Contributors: Various AnonymousDonors, TomAnderson, EarleMartin

This is the type of problem in which CollectionOrientedProgramming languages are clearly better geared for.

Also see CounterInManyProgrammingLanguages, DotProductInManyProgrammingLanguages, HelloWorldInManyProgrammingLanguages, WardNumberInManyProgrammingLanguages, BetterForLoopConstruct

CategoryInManyProgrammingLanguages

EditText of this page (last edited September 30, 2014) or FindPage with title or text search