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

From CodeCodex

(Haskell)
 
(25 intermediate revisions by 16 users not shown)
Line 1: Line 1:
[http://blhestrie.125mb.com/web/riforma-del/ riforma del codice di procedura civile] [http://champ-alnite.angelfire.com/libro-bimbo.htm libro bimbo] [http://awihimmeru.angelfire.com/il-gusto.htm il gusto del vino] [http://yarobiso.angelfire.com/text/foto-ostaggi.htm foto ostaggi nepalesi] [http://nescogin.125mb.com/content/gunny-bunny.htm gunny bunny] [http://wiellico.125mb.com/html/pranzo-al.htm pranzo al ritz] [http://stjollay.125mb.com/topic/mx-plantronics/ mx150 plantronics] [http://nescogin.125mb.com/content/m-i.htm m i a] [http://blhestrie.125mb.com/web/the-end/ the end] [http://stjollay.125mb.com/topic/volare-mp/ volare mp3] [http://fikimber.125mb.com/lib/www-actionchat.htm www actionchat] [http://dacornel.125mb.com/data/dm.htm dm 12 4 96] [http://bedrew.125mb.com/karma-malo.htm karma malo] [http://sewehner.125mb.com/articles/www-via/ www via michelin it] [http://paryker.125mb.com/styles/singole-maggiorate/ singole maggiorate] [http://dleslis.125mb.com/resources/il-drago.htm il drago degli abissi] [http://nescogin.125mb.com/content/trani-italia.htm trani italia] [http://bedrew.125mb.com/ovni.htm ovni] [http://dleslis.125mb.com/resources/biglietti-per.htm biglietti per concerto] [http://elernst.angelfire.com/articles/incontro-lerici.htm incontro lerici] [http://yarobiso.angelfire.com/text/nokia-i.htm nokia 6610i mms] [http://spdinnie.angelfire.com/html/univison-com/ univison com] [http://mcclaise.angelfire.com/description/gojko-mitic/ gojko mitic] [http://tibrown.125mb.com/description/leticia-spiler/ leticia spiler] [http://spdinnie.angelfire.com/html/adler-thermae/ adler thermae com] [http://vegrigsb.angelfire.com/resources/brother-mfc.htm brother mfc 7420] [http://awihimmeru.angelfire.com/celebridades-lesbianas.htm celebridades lesbianas] [http://gitedy.125mb.com/blog/congedo-parentale/ congedo parentale] [http://blhestrie.125mb.com/web/florida-mappa/ florida mappa] [http://stjollay.125mb.com/topic/everyone-be/ everyone be somebody] [http://paryker.125mb.com/styles/voli-per/ voli per djerba] [http://kocarawf.125mb.com/blog/kaitec.htm kaitec] [http://blhestrie.125mb.com/web/top/ top66] [http://gistrate.angelfire.com/html/supporto-per.htm supporto per palmari da auto] [http://gistrate.angelfire.com/html/el-confidente.htm el confidente] [http://grdugans.angelfire.com/text/mercedes-c.htm mercedes c 250 td esprit] [http://dleslis.125mb.com/resources/il-presagio.htm il presagio] [http://sewehner.125mb.com/articles/indios-tabajara/ indios tabajara] [http://dleslis.125mb.com/resources/mutuo-fisso.htm mutuo fisso] [http://yonosoyyo.angelfire.com/directory/tastiera-ad.htm tastiera ad infrarossi] [http://kocarawf.125mb.com/blog/gl.htm gl] [http://dleslis.125mb.com/resources/wireless-sd.htm wireless sd] [http://dleslis.125mb.com/resources/jun-kunimura.htm jun kunimura] [http://mamans.125mb.com/topic/atack.htm atack] [http://ruwier.125mb.com/caricabatteria-nimh/ caricabatteria nimh] [http://awihimmeru.angelfire.com/dural-spa.htm dural spa] [http://blhestrie.125mb.com/web/trasmissione-dati/ trasmissione dati] [http://sewehner.125mb.com/articles/cerco-cavalli/ cerco cavalli] [http://gitedy.125mb.com/blog/colin-firth/ colin firth] [http://sewehner.125mb.com/articles/riscaldamento-casa/ riscaldamento casa] [http://hoadmoni.125mb.com/styles/allison-and/ allison and williams] [http://dleslis.125mb.com/resources/la-genesi.htm la genesi di un maestro] [http://kocarawf.125mb.com/blog/gps-tomtom.htm gps tomtom nokia 6600] [http://ruwier.125mb.com/hanno-ucciso/ hanno ucciso il gioco calcio mp3] [http://gistrate.angelfire.com/html/tv-sony.htm tv sony plasma 42 pollici] [http://yonosoyyo.angelfire.com/directory/saucony-grid.htm saucony grid] [http://blhestrie.125mb.com/web/el-oro/ el oro] [http://fikimber.125mb.com/lib/media-hard.htm media hard disk e floppy] [http://gitedy.125mb.com/blog/barreto-jr/ barreto jr] [http://dleslis.125mb.com/resources/boris-karloff.htm boris karloff] [http://hoadmoni.125mb.com/styles/foto-uomini/ foto uomini col cazzo duro] [http://hoadmoni.125mb.com/styles/il-messaggio/ il messaggio di mettete dei fiori nei vostri cannoni] [http://degaylor.125mb.com/virginia-ristorante/ virginia ristorante] [http://sewehner.125mb.com/articles/il-primo/ il primo premio si chiama irene] [http://paryker.125mb.com/styles/world-golf/ world golf in english] [http://sawilson.125mb.com/data/corsi-rumba.htm corsi rumba torino] [http://vegrigsb.angelfire.com/resources/apple-dock.htm apple dock] [http://ruwier.125mb.com/fotocamere-yakumo/ fotocamere yakumo] [http://gitedy.125mb.com/blog/salvados-por/ salvados por la campana] [http://spdinnie.angelfire.com/html/kiloutou/ kiloutou] [http://wiellico.125mb.com/html/oakley-accessori.htm oakley accessori] [http://bedrew.125mb.com/la-figa.htm la figa di monica bellucci] [http://slavfondmeister.angelfire.com/styles/executive-service.htm executive service] [http://ruwier.125mb.com/kesenai-tsumi/ kesenai tsumi] [http://slavfondmeister.angelfire.com/styles/how-would.htm how would u feel] [http://wiellico.125mb.com/html/teen-sex.htm teen sex videos] [http://anethel.angelfire.com/comune-di.htm comune di treviso] [http://bedrew.125mb.com/bari-vibo.htm bari vibo valentia] [http://amarymuk.angelfire.com/html/telecomando-meliconi.htm telecomando meliconi] [http://amarymuk.angelfire.com/html/foto-offspring.htm foto offspring] [http://dleslis.125mb.com/resources/lettori-audio.htm lettori audio mp3] [http://vegrigsb.angelfire.com/resources/il-cuore.htm il cuore come amore] [http://dleslis.125mb.com/resources/duel-masters.htm duel masters vol 2] [http://tibrown.125mb.com/description/revolucion/ revolucion] [http://hoadmoni.125mb.com/styles/micro-maniacs/ micro maniacs] [http://gistrate.angelfire.com/html/inmortal.htm inmortal] [http://awihimmeru.angelfire.com/fotos-de.htm fotos de claveles] [http://nescogin.125mb.com/content/www-cinema.htm www cinema ugc fr] [http://nescogin.125mb.com/content/i-manga.htm i manga a 128 bit] [http://awihimmeru.angelfire.com/gadget-sportivi.htm gadget sportivi] [http://sewehner.125mb.com/articles/java-free/ java free] [http://kocarawf.125mb.com/blog/www-ciee.htm www ciee org br] [http://awihimmeru.angelfire.com/winzip-per.htm winzip per windows xp] [http://dleslis.125mb.com/resources/incredimail-gutterball.htm incredimail gutterball] [http://dleslis.125mb.com/resources/universita-dams.htm universita dams] [http://nescogin.125mb.com/content/jeonju.htm jeonju] [http://sewehner.125mb.com/articles/pentax-optio/ pentax optio mx] [http://mamans.125mb.com/topic/grand-theft.htm grand theft auto psp] [http://gistrate.angelfire.com/html/le-metropole.htm le metropole] [http://dacornel.125mb.com/data/chiarly.htm chiarly] [http://paryker.125mb.com/styles/midnight-club/ midnight club 3 la prossima settimana in italia] [http://stjollay.125mb.com/topic/micene/ micene] [http://awihimmeru.angelfire.com/epson-stylus.htm epson stylus photo 810] [http://yonosoyyo.angelfire.com/directory/pensiline.htm pensiline] [http://tibrown.125mb.com/description/celestina/ celestina] [http://hoadmoni.125mb.com/styles/cartelle-infermieristiche/ cartelle infermieristiche] [http://sawilson.125mb.com/data/cockatil.htm cockatil] [http://blhestrie.125mb.com/web/videoregistratore-super/ videoregistratore super vhs] [http://gitedy.125mb.com/blog/carpentier-y/ carpentier y valmont alejo] [http://wiellico.125mb.com/html/teac-gb.htm teac 40gb] [http://degaylor.125mb.com/torino-manila/ torino manila] [http://amarymuk.angelfire.com/html/timer-caffettiera.htm timer caffettiera] [http://wiellico.125mb.com/html/tm.htm tm 8100] [http://mamans.125mb.com/topic/mondo-erotico.htm mondo erotico] [http://yonosoyyo.angelfire.com/directory/www-bambola.htm www bambola club it] [http://morudd.angelfire.com/web/fabra-pompeu/ fabra pompeu] [http://gitedy.125mb.com/blog/pinocchia/ pinocchia] [http://paryker.125mb.com/styles/concorsi-carabinieri/ concorsi carabinieri riservato volontari] [http://sawilson.125mb.com/data/tachicardia.htm tachicardia] [http://nescogin.125mb.com/content/principessina.htm principessina] [http://stjollay.125mb.com/topic/braun-frullatore/ braun frullatore] [http://requidim.angelfire.com/web/ram-mhz.htm ram 133mhz 256mb] [http://fikimber.125mb.com/lib/doom-.htm doom 3 mod] [http://hoadmoni.125mb.com/styles/lavoro-a/ lavoro a legnago] [http://morudd.angelfire.com/web/siti-di/ siti di streghe] [http://sewehner.125mb.com/articles/biliardo-classics/ biliardo classics] [http://bedrew.125mb.com/casi-hong.htm casi hong nhung] [http://stjollay.125mb.com/topic/tn/ tn 11] [http://nescogin.125mb.com/content/www-virgilio.htm www virgilio it] [http://wiellico.125mb.com/html/linksys-ag.htm linksys ag241 modem] [http://dacornel.125mb.com/data/apple-imac.htm apple imac g5 17] [http://tibrown.125mb.com/description/takeshi-kitano/ takeshi kitano] [http://sawilson.125mb.com/data/adidas-scarpe.htm adidas scarpe skateboard] [http://morudd.angelfire.com/web/www-foxx/ www foxx equipment com] [http://dleslis.125mb.com/resources/cazzi-di.htm cazzi di cavallo] [http://paryker.125mb.com/styles/registratore-di/ registratore di minidisc] [http://wiellico.125mb.com/html/dragostea-din.htm dragostea din tei mid] [http://stjollay.125mb.com/topic/www-sat/ www sat com] [http://sibeatri.angelfire.com/html/kenwood-autoradio/ kenwood autoradio con dvd] [http://hoadmoni.125mb.com/styles/stampante-hp/ stampante hp designjet 110 plus] [http://sawilson.125mb.com/data/ratchet-gladiator.htm ratchet gladiator] [http://anethel.angelfire.com/ipod-cellulari.htm ipod cellulari] [http://dacornel.125mb.com/data/ddr-memoria.htm ddr2 memoria ram] [http://gistrate.angelfire.com/html/attrezzatura-campeggio.htm attrezzatura campeggio] [http://ruwier.125mb.com/hp-xeon/ hp xeon computer] [http://hoadmoni.125mb.com/styles/le-cap/ le cap] [http://stjollay.125mb.com/topic/i-gocha/ i gocha] [http://nescogin.125mb.com/content/lifeview-duo.htm lifeview duo] [http://gitedy.125mb.com/blog/scheda-asus/ scheda asus video] [http://tibrown.125mb.com/description/croak/ croak] [http://kocarawf.125mb.com/blog/una-data.htm una data per ace combat 4] [http://dacornel.125mb.com/data/hattaway.htm hattaway] [http://ruwier.125mb.com/change-your/ change your heart] [http://stjollay.125mb.com/topic/golf-iv/ golf iv volkswagen] [http://fikimber.125mb.com/lib/rock-roll.htm rock roll is dead] [http://hoadmoni.125mb.com/styles/robotics-modem/ robotics modem fax 56] [http://paryker.125mb.com/styles/web-mail/ web mail] [http://dacornel.125mb.com/data/tamburo-rullante.htm tamburo rullante] [http://amarymuk.angelfire.com/html/oasis-all.htm oasis all around the world] [http://anethel.angelfire.com/frontalino-sony.htm frontalino sony] [http://elernst.angelfire.com/articles/monika-brodka.htm monika brodka mp3] [http://hoadmoni.125mb.com/styles/elenco-partecipanti/ elenco partecipanti miss italia 2004] [http://ruwier.125mb.com/hp-business/ hp business inkjet 2800] [http://champ-alnite.angelfire.com/grazie-per.htm grazie per quel caldo dicembre] [http://sewehner.125mb.com/articles/pesca-tripode/ pesca tripode] [http://hoadmoni.125mb.com/styles/ospedale-de/ ospedale de best di milano] [http://blhestrie.125mb.com/web/amplificatori-classe/ amplificatori classe] [http://blhestrie.125mb.com/web/video-strani/ video strani] [http://yonosoyyo.angelfire.com/directory/le-motorizzate.htm le motorizzate] [http://sewehner.125mb.com/articles/que-es/ que es la administracion] [http://grdugans.angelfire.com/text/herrera.htm herrera] [http://vegrigsb.angelfire.com/resources/ragazze-di.htm ragazze di salerno] [http://sewehner.125mb.com/articles/canon/ canon 3200] [http://sewehner.125mb.com/articles/rs-dv/ rs dv multi media card] [http://dleslis.125mb.com/resources/manifestazioni-sanremo.htm manifestazioni sanremo] [http://degaylor.125mb.com/abbigliamento-uomo/ abbigliamento uomo pelle] [http://hoadmoni.125mb.com/styles/albergo-stella/ albergo stella] [http://ruwier.125mb.com/jeans-vita/ jeans vita bassa uomo] [http://sibeatri.angelfire.com/html/dsl-modem/ dsl modem firewall] [http://wiellico.125mb.com/html/hepu.htm hepu] [http://fikimber.125mb.com/lib/bert.htm bert] [http://sewehner.125mb.com/articles/veneto-moto/ veneto moto usate] [http://anethel.angelfire.com/quattro-nuovi.htm quattro nuovi dvd super] [http://yonosoyyo.angelfire.com/directory/auto-gas.htm auto gas] [http://degaylor.125mb.com/macchine-gare/ macchine gare] [http://blhestrie.125mb.com/web/stefania-belmondo/ stefania belmondo] [http://ruwier.125mb.com/siti-amatoriali/ siti amatoriali] [http://blhestrie.125mb.com/web/hp-all/ hp all in one a3] [http://hahosmer.angelfire.com/html/like-a.htm like a payer] [http://slavfondmeister.angelfire.com/styles/accessori-fujifilm.htm accessori fujifilm s5000] [http://slavfondmeister.angelfire.com/styles/nubira-gpl.htm nubira gpl] [http://degaylor.125mb.com/danger-zone/ danger zone 2] [http://tibrown.125mb.com/description/dagostea-tea/ dagostea tea din tei] [http://morudd.angelfire.com/web/athlon-/ athlon 64 3200 core venice] [http://blhestrie.125mb.com/web/inchiostri-solidi/ inchiostri solidi] [http://tibrown.125mb.com/description/roma-delhi/ roma delhi biglietti aerei] [http://morudd.angelfire.com/web/volo-last/ volo last minute canarie] [http://bedrew.125mb.com/trucci.htm trucci] [http://hoadmoni.125mb.com/styles/bad-moon/ bad moon rising] [http://amarymuk.angelfire.com/html/rio-diablos.htm rio diablos] {{Infobox See Also Math}}
+
{{Infobox See Also Math}}
 
This code demonstrates how to calculate the sum of a container (most often an array or similar structure).
 
This code demonstrates how to calculate the sum of a container (most often an array or similar structure).
  
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
 +
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
 +
</pre>
  
int total( int first, ... ) {
+
===C===
   int count = 0, sum = 0, i = first;
+
<pre class="c">
   va_list marker;
+
int total( int numbers[], int size ) {
 
+
   int sum = 0, i;
  va_start( marker, first );    /* Initialize variable arguments. */
+
   for ( i = 0 ; i < size ; i++ )
  while( i != INT_MAX )
+
 
   {
 
   {
       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>
+
<pre class="lisp">
(reduce #' list)
+
(reduce #'+ list)
 +
(reduce #'+ list :initial-value 0) ; improved version that also works with empty lists
 
</pre>
 
</pre>
  
 
Another way:
 
Another way:
  
 +
<pre class="lisp">
 +
(apply #'+ list)
 +
</pre>
 +
 +
===Erlang===
 
<pre>
 
<pre>
(apply #'  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 class="haskell">
 +
sum container
 +
</pre>
 +
For example:
 
<pre>
 
<pre>
sum container
+
Prelude> sum [1, 2, 3, 4]
 +
10
 
</pre>
 
</pre>
  
 
===Java===
 
===Java===
<pre>
+
<pre class="java">
 
import java.util.*;
 
import java.util.*;
  
Line 100: 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 115: 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 125: Line 138:
  
 
===Perl===
 
===Perl===
<HIGHLIGHTSYNTAX language="perl">
+
<pre class="perl">
 
use List::Util qw(sum);
 
use List::Util qw(sum);
 
sum @arr;
 
sum @arr;
</HIGHLIGHTSYNTAX>
+
sum 0, @arr; # improved version that also works with empty arrays
 +
</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 157: Line 190:
 
[[Category:Arrays]]
 
[[Category:Arrays]]
  
[[Category:C]]
+
[[Category:Algol 68]]
[[Category:C plus plus]]
+
 
[[Category:Assembly]]
 
[[Category:Assembly]]
 +
[[Category:C]]
 +
[[Category:C++]]
 +
[[Category:Common Lisp]]
 +
[[Category:Erlang]]
 +
[[Category:Excel]]
 +
[[Category:F sharp]]
 +
[[Category:Haskell]]
 
[[Category:Java]]
 
[[Category:Java]]
[[Category:OCaml]]
+
[[Category:Objective Caml]]
 
[[Category:Perl]]
 
[[Category:Perl]]
 
[[Category:Python]]
 
[[Category:Python]]
[[Category:Objective Caml]]
 
 
[[Category:Ruby]]
 
[[Category:Ruby]]
[[Category:Algol 68]]
+
[[Category:Scheme]]
[[Category:Common Lisp]]
+
[[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
}