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

From CodeCodex

(Python)
Line 92: Line 92:
 
[[Category:Java]]
 
[[Category:Java]]
 
[[Category:Python]]
 
[[Category:Python]]
[[Category:OCaml]]
+
[[Category:Objective Caml]]

Revision as of 14:57, 6 June 2006

Implementations

C

Total of a series function. Terminate by using INT_MAX

//stdarg.h must be included for this type of function to be declared
#include <stdarg.h>

int total( int first, ... ) {
   int count = 0, sum = 0, i = first;
   va_list marker;

   va_start( marker, first );     /* Initialize variable arguments. */
   while( i != INT_MAX )
   {
      sum += i;                   //increases the sum
      i = va_arg( marker, int);   //Gets the next argument
   }
   va_end( marker );              // Resets the list
   return sum;
}

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


Java

import java.util.*;

public class Total {

    public static int total(int... values) {
        int total = 0;
        for (int i : values) {
            if (i == Integer.MAX_VALUE) break;
            total +=i;
        }
       
        return total;
    }

    public static void main(String[] args) {

        System.out.printf("Total: %d: ", total(1,2,4,40,Integer.MAX_VALUE));
        
    }
}

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>
# sum [1; 2; 4; 40];;
- : int = 47

Python

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

if __name__ == '__main__':
  assert sum([1,2,3]) == 6

A parallel to the ANSI C example given above is as follows:

import itertools
def total(*values):
  return sum(itertools.takewhile(sys.maxint.__cmp__, values))

if __name__ == '__main__':
  assert total(1,2,3,sys.maxint) == 6