Difference between revisions of "Calculate the sum over a container"

From CodeCodex

(Haskell)
 
(34 intermediate revisions by 21 users not shown)
Line 12: Line 12:
 
The following function computes the sum of the elements of the array passed to it. The type of the array elements is called <TT>NUM</TT>, which can be defined as any suitable integer or real type.
 
The following function computes the sum of the elements of the array passed to it. The type of the array elements is called <TT>NUM</TT>, which can be defined as any suitable integer or real type.
  
<pre>MODE NUM = INT; # type of array element #
+
<pre>
 +
MODE NUM = INT; # type of array element #
  
 
PROC sum = ([] NUM a) NUM :
 
PROC sum = ([] NUM a) NUM :
Line 18: Line 19:
 
         NUM result := 0;
 
         NUM result := 0;
 
         FOR i FROM LWB a TO UPB a DO
 
         FOR i FROM LWB a TO UPB a DO
             result := a[i]
+
             result +:= a[i]
 
         OD;
 
         OD;
 
         result
 
         result
Line 26: Line 27:
 
For instance, the call
 
For instance, the call
  
<pre>sum((3, 4, 5, 6))
+
<pre>
 +
sum((3, 4, 5, 6))
 
</pre>
 
</pre>
 
returns 18.
 
returns 18.
  
 
+
===Assembly===
===C===
+
INT_MAX = 2147483647.
Total of a series function.  Terminate by using INT_MAX
+
 
<pre>
 
<pre>
//stdarg.h must be included for this type of function to be declared
+
sum proc
#include <stdarg.h>
+
mov ecx,DWORD PTR [esp]
 
+
add esp,4
int total( int first, ... ) {
+
xor eax,eax
  int count = 0, sum = 0, i = first;
+
sum_loop1:
  va_list marker;
+
add eax,DWORD PTR [esp]
 +
add esp,4
 +
cmp DWORD PTR [esp],2147483647
 +
jne sum_loop1
 +
mov DWORD PTR [esp],ecx
 +
ret
 +
sum endp
 +
</pre>
  
  va_start( marker, first );     /* Initialize variable arguments. */
+
===C===
   while( i != INT_MAX )
+
<pre class="c">
 +
int total( int numbers[], int size ) {
 +
  int sum = 0, i;
 +
   for ( i = 0 ; i < size ; i++ )
 
   {
 
   {
       sum = i;                   //increases the sum
+
       sum += numbers[i];
      i = va_arg( marker, int);  //Gets the next argument
+
 
   }
 
   }
  va_end( marker );              // Resets the list
 
 
   return sum;
 
   return sum;
 
}
 
}
 
</pre>
 
</pre>
  
===C ===
+
===C++===
<pre>
+
<pre class="cpp">
 
#include<numeric>
 
#include<numeric>
  
sum = accumulate(coll.begin(),coll.end(),0);
+
sum = std::accumulate(coll.begin(),coll.end(),0);
 
</pre>
 
</pre>
  
 
===Common Lisp===
 
===Common Lisp===
 +
<pre class="lisp">
 +
(reduce #'+ list)
 +
(reduce #'+ list :initial-value 0) ; improved version that also works with empty lists
 +
</pre>
 +
 +
Another way:
 +
 +
<pre class="lisp">
 +
(apply #'+ list)
 +
</pre>
 +
 +
===Erlang===
 
<pre>
 
<pre>
(reduce #'  list)
+
lists:sum(List).
 
</pre>
 
</pre>
  
===Assembly===
+
===Excel===
INT_MAX = 2147483647.
+
 
<pre>
 
<pre>
sum proc
+
=SUM([cells])
mov ecx,DWORD PTR [esp]
+
</pre>
add esp,4
+
 
xor eax,eax
+
===F#===
sum_loop1:
+
<pre class="fsharp">
add eax,DWORD PTR [esp]
+
Seq.sum container
add esp,4
+
cmp DWORD PTR [esp],2147483647
+
jne sum_loop1
+
mov DWORD PTR [esp],ecx
+
ret
+
sum endp
+
 
</pre>
 
</pre>
  
 
===Haskell===
 
===Haskell===
<pre>
+
<pre class="haskell">
 
sum container
 
sum container
 +
</pre>
 +
For example:
 +
<pre>
 +
Prelude> sum [1, 2, 3, 4]
 +
10
 
</pre>
 
</pre>
  
 
===Java===
 
===Java===
<pre>
+
<pre class="java">
 
import java.util.*;
 
import java.util.*;
  
Line 94: Line 113:
 
     public static int total(int... values) {
 
     public static int total(int... values) {
 
         int total = 0;
 
         int total = 0;
         for (int i : values) total = i;       
+
         for (int i : values) total += i;       
 
         return total;
 
         return total;
 
     }
 
     }
Line 109: Line 128:
 
Summing is a special case of folding the addition operator starting with zero:
 
Summing is a special case of folding the addition operator starting with zero:
 
<pre>
 
<pre>
# let sum = List.fold_left (   ) 0;;
+
# let sum = List.fold_left ( + ) 0;;
 
val sum : int list -> int = <fun>
 
val sum : int list -> int = <fun>
 
</pre>
 
</pre>
Line 116: Line 135:
 
# sum [1; 2; 4; 40];;
 
# sum [1; 2; 4; 40];;
 
- : int = 47
 
- : int = 47
 +
</pre>
 +
 +
===Perl===
 +
<pre class="perl">
 +
use List::Util qw(sum);
 +
sum @arr;
 +
sum 0, @arr; # improved version that also works with empty arrays
 
</pre>
 
</pre>
  
 
===Python===
 
===Python===
 
A function that sums the values in a sequence is built into python, its name is 'sum'.
 
A function that sums the values in a sequence is built into python, its name is 'sum'.
<pre>
+
<pre class="python">
if __name__ == '__main__':
+
assert sum([1,2,3]) == 6
  assert sum([1,2,3]) == 6
+
 
</pre>
 
</pre>
A parallel to the ANSI C example given above is as follows:
 
<pre>
 
import itertools
 
def total(*values):
 
  return sum(itertools.takewhile(sys.maxint.__cmp__, values))
 
  
if __name__ == '__main__':
+
===Ruby===
   assert total(1,2,3,sys.maxint) == 6
+
<pre class="ruby">
 +
class Array
 +
   def sum
 +
    inject { |s, v| s += v }
 +
  end
 +
end
 +
</pre>
 +
Or more concisely,  
 +
<pre class="ruby">
 +
class Array
 +
  def sum
 +
    reduce(:+)
 +
  end
 +
end
 
</pre>
 
</pre>
  
 +
===Scheme===
 +
<pre class="scheme">
 +
(apply + list)
 +
</pre>
  
===Ruby===
+
===Tcl===
 +
<pre class="tcl">
 +
proc sum list {expr ([join $list +])}
 +
</pre>
 +
 
 +
===Zsh===
 
<pre>
 
<pre>
class Array
+
zsum() {
  def sum;    inject(0) { |s, v| s  = v }; end
+
local -a array
end
+
array=(1 2 3 4 5)
 +
(( sum=${(j:+:)array} ))
 +
return sum
 +
}
 
</pre>
 
</pre>
  
Line 145: Line 190:
 
[[Category:Arrays]]
 
[[Category:Arrays]]
  
 +
[[Category:Algol 68]]
 +
[[Category:Assembly]]
 
[[Category:C]]
 
[[Category:C]]
[[Category:C plus plus]]
+
[[Category:C++]]
[[Category:Assembly]]
+
[[Category:Common Lisp]]
 +
[[Category:Erlang]]
 +
[[Category:Excel]]
 +
[[Category:F sharp]]
 +
[[Category:Haskell]]
 
[[Category:Java]]
 
[[Category:Java]]
 +
[[Category:Objective Caml]]
 +
[[Category:Perl]]
 
[[Category:Python]]
 
[[Category:Python]]
[[Category:Objective Caml]]
 
 
[[Category:Ruby]]
 
[[Category:Ruby]]
[[Category:Algol 68]]
+
[[Category:Scheme]]
 +
[[Category:Tcl]]
 +
[[Category:Zsh]]

Latest revision as of 15:50, 10 August 2012

Related content:

This code demonstrates how to calculate the sum of a container (most often an array or similar structure).

See also[edit]

Implementations[edit]

Algol 68[edit]

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.

Assembly[edit]

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

C[edit]

int total( int numbers[], int size ) {
   int sum = 0, i;
   for ( i = 0 ; i < size ; i++ )
   {
      sum += numbers[i];
   }
   return sum;
}

C++[edit]

#include<numeric>

sum = std::accumulate(coll.begin(),coll.end(),0);

Common Lisp[edit]

(reduce #'+ list)
(reduce #'+ list :initial-value 0) ; improved version that also works with empty lists

Another way:

(apply #'+ list)

Erlang[edit]

lists:sum(List).

Excel[edit]

=SUM([cells])

F#[edit]

Seq.sum container

Haskell[edit]

sum container

For example:

Prelude> sum [1, 2, 3, 4]
10

Java[edit]

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));
        
    }
}

OCaml[edit]

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

Perl[edit]

use List::Util qw(sum);
sum @arr;
sum 0, @arr; # improved version that also works with empty arrays

Python[edit]

A function that sums the values in a sequence is built into python, its name is 'sum'.

assert sum([1,2,3]) == 6

Ruby[edit]

class Array
  def sum
    inject { |s, v| s += v }
  end
end

Or more concisely,

class Array
  def sum
    reduce(:+)
  end
end

Scheme[edit]

(apply + list)

Tcl[edit]

proc sum list {expr ([join $list +])}

Zsh[edit]

zsum() {
	local -a array
	array=(1 2 3 4 5)
	(( sum=${(j:+:)array} ))
	return sum
}