Sum and product of an array: Difference between revisions
Content added Content deleted
(rm what seems a duplicate, even if a little bit different in syntax (Standard ML twice)) |
m (Highlighting, whitespace) |
||
Line 1: | Line 1: | ||
{{task|Arithmetic operations}}[[Category:Iteration]] |
{{task|Arithmetic operations}}[[Category:Iteration]] |
||
Compute the sum and product of an array of integers. |
Compute the sum and product of an array of integers. |
||
=={{header|4D}}== |
=={{header|4D}}== |
||
<lang 4d>ARRAY INTEGER($list;0) |
|||
For ($i;1;5) |
|||
APPEND TO ARRAY($list;$i) |
|||
End for |
|||
$sum:=0 |
|||
$product:=1 |
|||
For ($i;1;Size of array($list)) |
|||
$sum:=$var+$list{$i} |
|||
$product:=$product*$list{$i} |
|||
End for |
|||
$sum:=0 |
|||
$product:=1 |
|||
For ($i;1;Size of array($list)) |
|||
$sum:=$var+$list{$i} |
|||
$product:=$product*$list{$i} |
|||
End for</lang> |
|||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
<lang actionscript> |
<lang actionscript>package { |
||
package { |
|||
import flash.display.Sprite; |
import flash.display.Sprite; |
||
Line 38: | Line 35: | ||
} |
} |
||
} |
} |
||
}</lang> |
|||
} |
|||
</lang> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
<lang ada>type Int_Array is array(Integer range <>) of Integer; |
|||
<lang ada> |
|||
type Int_Array is array(Integer range <>) of Integer; |
|||
array : Int_Array := (1,2,3,4,5,6,7,8,9,10); |
|||
Sum : Integer := 0; |
|||
for I in array'range loop |
|||
Sum := Sum + array(I); |
|||
end loop;</lang> |
|||
</lang> |
|||
Define the product function |
Define the product function |
||
<lang ada>function Product(Item : Int_Array) return Integer is |
|||
<lang ada> |
|||
Prod : Integer := 1; |
|||
begin |
|||
Prod : Integer := 1; |
|||
for I in Item'range loop |
|||
begin |
|||
Prod := Prod * Item(I); |
|||
for I in Item'range loop |
|||
end loop; |
|||
Prod := Prod * Item(I); |
|||
return Prod; |
|||
end Product;</lang> |
|||
return Prod; |
|||
end Product; |
|||
</lang> |
|||
This function will raise the predefined exception Constraint_Error if the product overflows the values represented by type Integer |
This function will raise the predefined exception Constraint_Error if the product overflows the values represented by type Integer |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
<lang algol68>main:( |
|||
INT default upb := 3; |
|||
MODE INTARRAY = [default upb]INT; |
|||
INTARRAY array = (1,2,3,4,5,6,7,8,9,10); |
|||
INT sum := 0; |
|||
FOR i FROM LWB array TO UPB array DO |
|||
sum +:= array[i] |
|||
OD; |
|||
# Define the product function # |
|||
PROC int product = (INTARRAY item)INT: |
|||
( |
|||
INT prod :=1; |
|||
FOR i FROM LWB item TO UPB item DO |
|||
prod *:= item[i] |
|||
OD; |
|||
prod |
|||
) # int product # ; |
|||
printf(($" Sum: "g(0)$,sum,$", Product:"g(0)";"l$,int product(array))) |
|||
)</lang> |
|||
) |
|||
Output: |
Output: |
||
Sum: 55, Product:3628800; |
Sum: 55, Product:3628800; |
||
Line 101: | Line 92: | ||
prod list |
prod list |
||
120 |
120 |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
<lang applescript>set array to {1, 2, 3, 4, 5} |
|||
set sum to 0 |
|||
set product to 1 |
|||
repeat with i in array |
|||
set sum to sum + i |
|||
set product to product * i |
|||
end repeat</lang> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
<lang AutoHotkey> |
<lang AutoHotkey>numbers = 1,2,3,4,5 |
||
numbers = 1,2,3,4,5 |
|||
product := 1 |
product := 1 |
||
loop, parse, numbers, `, |
loop, parse, numbers, `, |
||
Line 119: | Line 108: | ||
product *= A_LoopField |
product *= A_LoopField |
||
} |
} |
||
msgbox, sum = %sum%`nproduct = %product% |
msgbox, sum = %sum%`nproduct = %product%</lang> |
||
</lang> |
|||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
For array input, it is easiest to "deserialize" it from a string with the split() function. |
For array input, it is easiest to "deserialize" it from a string with the split() function. |
||
<lang awk>$ awk 'func sum(s){split(s,a);r=0;for(i in a)r+=a[i];return r}{print sum($0)}' |
|||
<lang awk> |
|||
$ awk 'func sum(s){split(s,a);r=0;for(i in a)r+=a[i];return r}{print sum($0)}' |
|||
1 2 3 4 5 6 7 8 9 10 |
1 2 3 4 5 6 7 8 9 10 |
||
55 |
55 |
||
Line 131: | Line 117: | ||
$ awk 'func prod(s){split(s,a);r=1;for(i in a)r*=a[i];return r}{print prod($0)}' |
$ awk 'func prod(s){split(s,a);r=1;for(i in a)r*=a[i];return r}{print prod($0)}' |
||
1 2 3 4 5 6 7 8 9 10 |
1 2 3 4 5 6 7 8 9 10 |
||
3628800 |
3628800</lang> |
||
</lang> |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
{{works with|QuickBasic|4.5}} |
|||
'''Interpreter:''' unknown |
|||
<lang qbasic>10 REM Create an array with some test data in it |
|||
20 DIM ARRAY(5) |
|||
30 FOR I = 1 TO 5: READ ARRAY(I): NEXT I |
|||
40 DATA 1, 2, 3, 4, 5 |
|||
50 REM Find the sum of elements in the array |
|||
60 SUM = 0 |
|||
65 PRODUCT = 1 |
|||
70 FOR I = 1 TO 5 |
|||
72 SUM = SUM + ARRAY(I) |
|||
75 PRODUCT = PRODUCT + ARRAY(I) |
|||
77 NEXT I |
|||
80 PRINT "The sum is ";SUM; |
|||
90 PRINT " and the product is ";PRODUCT</lang> |
|||
{{works with|FreeBASIC}} |
{{works with|FreeBASIC}} |
||
<lang freebasic>dim array(5) as integer = { 1, 2, 3, 4, 5 } |
|||
dim sum as integer = 0 |
|||
dim prod as integer = 1 |
|||
for index as integer = lbound(array) to ubound(array) |
|||
sum += array(index) |
|||
prod *= array(index) |
|||
next |
|||
dim sum as integer = 0 |
|||
dim prod as integer = 1 |
|||
for index as integer = lbound(array) to ubound(array) |
|||
sum += array(index) |
|||
prod *= array(index) |
|||
next</lang> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
<lang c>/* using pointer arithmetic (because we can, I guess) */ |
|||
int arg[] = { 1,2,3,4,5 }; |
|||
int arg_length = sizeof(arg)/sizeof(arg[0]); |
|||
int *end = arg+arg_length; |
|||
int sum = 0, prod = 1; |
|||
int *p; |
|||
for (p = arg; p!=end; ++p) { |
|||
sum += *p; |
|||
prod *= *p; |
|||
} |
|||
for (p = arg; p!=end; ++p) { |
|||
sum += *p; |
|||
prod *= *p; |
|||
}</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{libheader|STL}} |
{{libheader|STL}} |
||
<lang cpp>#include <numeric> |
|||
#include <functional> |
|||
int arg[] = { 1, 2, 3, 4, 5 }; |
|||
int sum = std::accumulate(arg, arg+5, 0, std::plus<int>()); |
|||
// or just |
|||
// std::accumulate(arg, arg + 5, 0); |
|||
// since plus() is the default functor for accumulate |
|||
int prod = std::accumulate(arg, arg+5, 1, std::multiplies<int>()); |
|||
int arg[] = { 1, 2, 3, 4, 5 }; |
|||
int sum = std::accumulate(arg, arg+5, 0, std::plus<int>()); |
|||
// or just |
|||
// std::accumulate(arg, arg + 5, 0); |
|||
// since plus() is the default functor for accumulate |
|||
int prod = std::accumulate(arg, arg+5, 1, std::multiplies<int>());</lang> |
|||
Template alternative: |
Template alternative: |
||
<lang cpp>// this would be more elegant using STL collections |
|||
template <typename T> T sum (const T *array, const unsigned n) |
|||
{ |
|||
T accum = 0; |
|||
for (unsigned i=0; i<n; i++) |
|||
accum += array[i]; |
|||
return accum; |
|||
} |
|||
template <typename T> T prod (const T *array, const unsigned n) |
|||
{ |
|||
T accum = 1; |
|||
for (unsigned i=0; i<n; i++) |
|||
accum *= array[i]; |
|||
return accum; |
|||
} |
|||
#include <iostream> |
|||
// this would be more elegant using STL collections |
|||
using std::cout; |
|||
template <typename T> T sum (const T *array, const unsigned n) |
|||
using std::endl; |
|||
{ |
|||
T accum = 0; |
|||
for (unsigned i=0; i<n; i++) |
|||
accum += array[i]; |
|||
return accum; |
|||
} |
|||
template <typename T> T prod (const T *array, const unsigned n) |
|||
{ |
|||
T accum = 1; |
|||
for (unsigned i=0; i<n; i++) |
|||
accum *= array[i]; |
|||
return accum; |
|||
} |
|||
#include <iostream> |
|||
using std::cout; |
|||
using std::endl; |
|||
int main () |
|||
{ |
|||
int aint[] = {1, 2, 3}; |
|||
cout << sum(aint,3) << " " << prod(aint, 3) << endl; |
|||
float aflo[] = {1.1, 2.02, 3.003, 4.0004}; |
|||
cout << sum(aflo,4) << " " << prod(aflo,4) << endl; |
|||
return 0; |
|||
} |
|||
int main () |
|||
{ |
|||
int aint[] = {1, 2, 3}; |
|||
cout << sum(aint,3) << " " << prod(aint, 3) << endl; |
|||
float aflo[] = {1.1, 2.02, 3.003, 4.0004}; |
|||
cout << sum(aflo,4) << " " << prod(aflo,4) << endl; |
|||
return 0; |
|||
}</lang> |
|||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
<lang csharp>int sum = 0, prod = 1; |
<lang csharp>int sum = 0, prod = 1; |
||
Line 225: | Line 203: | ||
=={{header|Clean}}== |
=={{header|Clean}}== |
||
<lang clean>array = {1, 2, 3, 4, 5} |
|||
Sum = sum [x \\ x <-: array] |
|||
Prod = foldl (*) 1 [x \\ x <-: array]</lang> |
|||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
Sum of an Array, |
Sum of an Array, |
||
<cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]> |
<cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]> |
||
<cfoutput>#ArraySum(Variables.myArray)#</cfoutput> |
<cfoutput>#ArraySum(Variables.myArray)#</cfoutput> |
||
Line 243: | Line 218: | ||
</cfloop> |
</cfloop> |
||
<cfoutput>#Variables.Product#</cfoutput> |
<cfoutput>#Variables.Product#</cfoutput> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
<lang lisp>(let ((data #(1 2 3 4 5))) ; the array |
<lang lisp>(let ((data #(1 2 3 4 5))) ; the array |
||
(values (reduce #'+ data) ; sum |
(values (reduce #'+ data) ; sum |
||
(reduce #'* data))) ; product</lang> |
(reduce #'* data))) ; product</lang> |
||
=={{header|D}}== |
=={{header|D}}== |
||
<lang d>auto sum = 0, prod = 1; |
<lang d>auto sum = 0, prod = 1; |
||
Line 263: | Line 235: | ||
writefln("Product: ", r._1); |
writefln("Product: ", r._1); |
||
</lang> |
</lang> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
<lang delphi>var |
|||
Ints : array[1..5] of integer = (1,2,3,4,5) ; |
|||
i,Sum : integer = 0 ; |
|||
Prod : integer = 1 ; |
|||
begin |
|||
for i := 1 to length(ints) do begin |
|||
inc(sum,ints[i]) ; |
|||
prod := prod * ints[i] |
|||
end; |
|||
end; |
end; |
||
end;</lang> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
<lang e>pragma.enable("accumulator") |
|||
accum 0 for x in [1,2,3,4,5] { _ + x } |
|||
accum 1 for x in [1,2,3,4,5] { _ * x }</lang> |
|||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
{{works with|XEmacs|version 21.5.21}} |
{{works with|XEmacs|version 21.5.21}} |
||
Line 290: | Line 259: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Using the standard libraries: |
Using the standard libraries: |
||
<lang erlang>% create the list: |
|||
L = lists:seq(1, 10). |
|||
% and compute its sum: |
|||
% create the list: |
|||
S = lists:sum(L). |
|||
P = lists:foldl(fun (X, P) -> X * P end, 1, L).</lang> |
|||
% and compute its sum: |
|||
S = lists:sum(L). |
|||
P = lists:foldl(fun (X, P) -> X * P end, 1, L). |
|||
Or defining our own versions: |
Or defining our own versions: |
||
<lang erlang>-module(list_sum). |
|||
-export([sum_rec/1, sum_tail/1]). |
|||
% recursive definition: |
|||
-module(list_sum). |
|||
sum_rec([]) -> |
|||
-export([sum_rec/1, sum_tail/1]). |
|||
0; |
|||
sum_rec([Head|Tail]) -> |
|||
% recursive definition: |
|||
Head + sum_rec(Tail). |
|||
0; |
|||
sum_rec([Head|Tail]) -> |
|||
Head + sum_rec(Tail). |
|||
% tail-recursive definition: |
|||
sum_tail(L) -> |
|||
sum_tail(L, 0). |
|||
sum_tail([], Acc) -> |
|||
Acc; |
|||
sum_tail([Head|Tail], Acc) -> |
|||
sum_tail(Tail, Head + Acc). |
|||
% tail-recursive definition: |
|||
sum_tail(L) -> |
|||
sum_tail(L, 0). |
|||
sum_tail([], Acc) -> |
|||
Acc; |
|||
sum_tail([Head|Tail], Acc) -> |
|||
sum_tail(Tail, Head + Acc).</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
1 5 1 <range> [ sum . ] [ product . ] bi |
1 5 1 <range> [ sum . ] [ product . ] bi |
||
Line 338: | Line 303: | ||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
In ISO Fortran 90 and later, use SUM and PRODUCT intrinsics: |
In ISO Fortran 90 and later, use SUM and PRODUCT intrinsics: |
||
<lang fortran>integer, dimension(10) :: a = (/ (i, i=1, 10) /) |
|||
integer :: sresult, presult |
|||
sresult = sum(a); |
|||
presult = product(a);</lang> |
|||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Groovy adds a "sum()" method for collections, but not a "product()" method: |
Groovy adds a "sum()" method for collections, but not a "product()" method: |
||
<lang groovy> |
<lang groovy>[1,2,3,4,5].sum()</lang> |
||
[1,2,3,4,5].sum() |
|||
</lang> |
|||
However, for general purpose "reduction" or "folding" operations, Groovy does provide an "inject()" method for collections similar to "inject" in Ruby. |
However, for general purpose "reduction" or "folding" operations, Groovy does provide an "inject()" method for collections similar to "inject" in Ruby. |
||
<lang groovy> |
<lang groovy>[1,2,3,4,5].inject(0) { sum, val -> sum + val } |
||
[1,2,3,4,5].inject(1) { prod, val -> prod * val }</lang> |
|||
[1,2,3,4,5].inject(1) { prod, val -> prod * val } |
|||
</lang> |
|||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
For lists, ''sum'' and ''product'' are already defined in the Prelude: |
For lists, ''sum'' and ''product'' are already defined in the Prelude: |
||
<lang haskell>values = [1..10] |
|||
values |
s = sum values -- the easy way |
||
p = product values |
|||
s = sum values -- the easy way |
|||
p = product values |
|||
s' = foldl (+) 0 values -- the hard way |
|||
p' = foldl (*) 1 values |
|||
s' = foldl (+) 0 values -- the hard way |
|||
p' = foldl (*) 1 values</lang> |
|||
To do the same for an array, just convert it lazily to a list: |
To do the same for an array, just convert it lazily to a list: |
||
<lang haskell>import Data.Array |
|||
values = listArray (1,10) [1..10] |
|||
import Data.Array |
|||
values = listArray (1,10) [1..10] |
|||
s = sum . elems $ values |
|||
p = product . elems $ values |
|||
s = sum . elems $ values |
|||
p = product . elems $ values</lang> |
|||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
array = [3,6,8] |
array = [3,6,8] |
||
Line 412: | Line 366: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
||
<lang |
<lang java5>public class SumProd{ |
||
public static void main(String[] args){ |
public static void main(String[] args){ |
||
int sum= 0; |
int sum= 0; |
||
Line 425: | Line 379: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
<lang javascript>var array = [1, 2, 3, 4, 5]; |
|||
var sum = 0, prod = 1; |
|||
for(var i in array) { |
|||
sum += array[i]; |
|||
prod *= array[i]; |
|||
} |
|||
alert(sum + " " + prod);</lang> |
|||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
<lang logo>print apply "sum arraytolist {1 2 3 4 5} |
|||
print apply "product arraytolist {1 2 3 4 5}</lang> |
|||
=={{header|Lucid}}== |
=={{header|Lucid}}== |
||
prints a running sum and product of sequence 1,2,3... |
prints a running sum and product of sequence 1,2,3... |
||
<lang lucid>[%sum,product%] |
|||
where |
|||
x = 1 fby x + 1; |
|||
sum = 0 fby sum + x; |
|||
product = 1 fby product * x |
|||
end</lang> |
|||
=={{header|Mathematica}}== |
=={{header|Mathematica}}== |
||
Mathematica provides many ways of doing the sum of an array (any kind of numbers or symbols): |
Mathematica provides many ways of doing the sum of an array (any kind of numbers or symbols): |
||
<lang Mathematica> |
<lang Mathematica>a = {1, 2, 3, 4, 5} |
||
Plus @@ a |
|||
a = {1, 2, 3, 4, 5} |
|||
Apply[Plus, a] |
|||
Total[a] |
|||
Apply[Plus, a] |
|||
Total@a |
|||
a // Total |
|||
Total@a |
|||
Sum[a[[i]], {i, 1, Length[a]}] |
|||
a // Total |
|||
Sum[i, {i, a}]</lang> |
|||
Sum[i, {i, a}] |
|||
</lang> |
|||
all give 15. For product we also have a couple of choices: |
all give 15. For product we also have a couple of choices: |
||
<lang Mathematica> |
<lang Mathematica>a = {1, 2, 3, 4, 5} |
||
Times @@ a |
|||
a = {1, 2, 3, 4, 5} |
|||
Apply[Times, a] |
|||
Product[a[[i]], {i, 1, Length[a]}] |
|||
Apply[Times, a] |
|||
Product[i, {i, a}]</lang> |
|||
Product[i, {i, a}] |
|||
</lang> |
|||
all give 120. |
all give 120. |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
<lang maxscript>arr = #(1, 2, 3, 4, 5) |
|||
sum = 0 |
|||
for i in arr do sum += i |
|||
product = 1 |
|||
for i in arr do product *= i</lang> |
|||
=={{header|Nial}}== |
=={{header|Nial}}== |
||
Nial being an array language, what applies to individual elements are extended to cover array operations by default |
Nial being an array language, what applies to individual elements are extended to cover array operations by default strand notation |
||
<lang nial>+ 1 2 3 |
|||
strand notation |
|||
= 6 |
|||
+ 1 2 3 |
|||
* 1 2 3 |
|||
= 6 |
|||
= 6</lang> |
|||
* 1 2 3 |
|||
= 6 |
|||
array notation |
array notation |
||
<lang nial>+ [1,2,3]</lang> |
|||
grouped notation |
grouped notation |
||
<lang nial>(* 1 2 3) |
|||
= 6 |
|||
* (1 2 3) |
|||
= 6</lang> |
|||
(All these notations are equivalent) |
(All these notations are equivalent) |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
<lang modula3>MODULE Sumprod EXPORTS Main; |
|||
<pre> |
|||
MODULE Sumprod EXPORTS Main; |
|||
FROM IO IMPORT Put; |
FROM IO IMPORT Put; |
||
Line 510: | Line 451: | ||
Put("Sum of array: " & Int(sum) & "\n"); |
Put("Sum of array: " & Int(sum) & "\n"); |
||
Put("Product of array: " & Int(prod) & "\n"); |
Put("Product of array: " & Int(prod) & "\n"); |
||
END Sumprod. |
END Sumprod.</lang> |
||
</pre> |
|||
Output: |
Output: |
||
<pre> |
<pre>Sum of array: 15 |
||
Product of array: 120</pre> |
|||
Product of array: 120 |
|||
</pre> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
{{works with|GCC|4.0.1 (apple)}} |
{{works with|GCC|4.0.1 (apple)}} |
||
Sum: |
Sum: |
||
<lang objc>- (float) sum:(NSMutableArray *)array |
|||
{ |
|||
int i, sum, value; |
|||
sum = 0; |
|||
value = 0; |
|||
for (i = 0; i < [array count]; i++) { |
|||
value = [[array objectAtIndex: i] intValue]; |
|||
sum += value; |
|||
} |
|||
return suml; |
|||
}</lang> |
|||
} |
|||
Product: |
Product: |
||
<lang objc>- (float) prod:(NSMutableArray *)array |
|||
{ |
|||
int i, prod, value; |
|||
prod = 0; |
|||
value = 0; |
|||
for (i = 0; i < [array count]; i++) { |
|||
value = [[array objectAtIndex: i] intValue]; |
|||
prod *= value; |
|||
} |
|||
return suml; |
|||
}</lang> |
|||
} |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
===Arrays=== |
|||
<lang ocaml>(* ints *) |
|||
let a = [| 1; 2; 3; 4; 5 |];; |
|||
Array.fold_left (+) 0 a;; |
|||
Array.fold_left ( * ) 1 a;; |
|||
(* floats *) |
|||
let a = [| 1.0; 2.0; 3.0; 4.0; 5.0 |];; |
|||
Array.fold_left (+.) 0.0 a;; |
|||
Array.fold_left ( *.) 1.0 a;;</lang> |
|||
===Lists=== |
|||
<lang ocaml>(* ints *) |
|||
'''Lists''' |
|||
let x = [1; 2; 3; 4; 5];; |
|||
(* ints *) |
|||
List.fold_left (+) 0 x;; |
|||
let x = [1; 2; 3; 4; 5];; |
|||
List.fold_left ( * ) 1 x;; |
|||
(* floats *) |
|||
List.fold_left ( * ) 1 x;; |
|||
let x = [1; 2; 3; 4; 5];; |
|||
(* floats *) |
|||
List.fold_left (+.) 0.0 x;; |
|||
let x = [1; 2; 3; 4; 5];; |
|||
List.fold_left ( *.) 1.0 x;;</lang> |
|||
List.fold_left ( *.) 1.0 x;; |
|||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
<lang octave>a = [ 1, 2, 3, 4, 5, 6 ]; |
<lang octave>a = [ 1, 2, 3, 4, 5, 6 ]; |
||
b = [ 10, 20, 30, 40, 50, 60 ]; |
b = [ 10, 20, 30, 40, 50, 60 ]; |
||
vsum = a + b; |
vsum = a + b; |
||
vprod = a .* b;</lang> |
vprod = a .* b;</lang> |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
<lang oz>functor |
|||
<pre> |
|||
functor |
|||
import |
import |
||
Application System |
Application System |
||
Line 595: | Line 523: | ||
{Application.exit 0} |
{Application.exit 0} |
||
end |
end</lang> |
||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
<lang perl>my ($sum, $prod) = (0, 1); |
|||
my @list = (1, 2, 3); |
|||
$sum += $_ foreach @list; |
|||
$prod *= $_ foreach @list;</lang> |
|||
Alternate: |
Alternate: |
||
{{libheader|List::Util}} |
{{libheader|List::Util}} |
||
<lang perl>use List::Util qw(sum reduce); |
|||
my @list = (1, 2, 3); |
|||
my $sum1 = sum 0, @list; # 0 identity to allow empty list |
|||
my $sum2 = reduce { $a + $b } 0, @list; |
|||
my $product = reduce { $a * $b } 1, @list; |
|||
my @list = (1, 2, 3); |
|||
my $sum1 = sum 0, @list; # 0 identity to allow empty list |
|||
my $sum2 = reduce { $a + $b } 0, @list; |
|||
my $product = reduce { $a * $b } 1, @list;</lang> |
|||
Alternate |
Alternate |
||
'''# TMTOWTDI''' |
'''# TMTOWTDI''' |
||
<lang perl>my ($sum, $prod) = (0, 1); |
|||
my @list = qw(1 2 3); |
|||
map { $sum += $_ } @list; |
|||
map($prod *= $_, @list);</lang> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
<lang php>$array = array(1,2,3,4,5,6,7,8,9); |
|||
echo array_sum($array); |
|||
echo array_product($array);</lang> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
Simple loop: |
Simple loop: |
||
<lang pop11>lvars i, sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9}; |
|||
for i from 1 to length(ar) do |
|||
lvars i, sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9}; |
|||
ar(i) + sum -> sum; |
|||
for i from 1 to length(ar) do |
|||
ar(i) * prod -> prod; |
|||
endfor;</lang> |
|||
ar(i) * prod -> prod; |
|||
endfor; |
|||
One can alternativly use second order iterator: |
One can alternativly use second order iterator: |
||
<lanf pop11>lvars sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9}; |
|||
appdata(ar, procedure(x); x + sum -> sum; endprocedure); |
|||
lvars sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9}; |
|||
appdata(ar, procedure(x); x * prod -> prod; endprocedure);</lang> |
|||
appdata(ar, procedure(x); x * prod -> prod; endprocedure); |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
The <code>Measure-Object</code> cmdlet already knows how to compute a sum: |
The <code>Measure-Object</code> cmdlet already knows how to compute a sum: |
||
Line 693: | Line 610: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
<lang prolog>sum([],0). |
|||
sum([H|T],X) :- sum(T,Y), X is H + Y. |
|||
product([],1). |
|||
product([H|T],X) :- product(T,Y), X is H * X.</lang> |
|||
test |
test |
||
Line 706: | Line 623: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{works with|Python|2.5}} |
{{works with|Python|2.5}} |
||
<lang python>numbers = [1, 2, 3] |
|||
total = sum(numbers) |
|||
product = 1 |
|||
for i in numbers: |
|||
product *= i |
|||
product = 1 |
|||
for i in numbers: |
|||
product *= i</lang> |
|||
Or functionally (faster but perhaps less clear): |
Or functionally (faster but perhaps less clear): |
||
{{works with|Python|2.5}} |
{{works with|Python|2.5}} |
||
<lang python>from operator import mul, add |
|||
sum = reduce(add, numbers) # note: this version doesn't work with empty lists |
|||
sum = reduce(add, numbers, 0) |
|||
product = reduce(mul, numbers) # note: this version doesn't work with empty lists |
|||
product = reduce(mul, numbers, 1)</lang> |
|||
{{libheader|numpy}} |
{{libheader|numpy}} |
||
<lang python>from numpy import r_ |
|||
numbers = r_[1:4] |
|||
total = numbers.sum() |
|||
product = numbers.prod()</lang> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
<lang r>arr <- c(1,2,3,4,5) |
|||
total <- sum(arr) |
|||
product <- prod(arr)</lang> |
|||
=={{header|Raven}}== |
=={{header|Raven}}== |
||
<lang raven>0 [ 1 2 3 ] each + |
|||
1 [ 1 2 3 ] each *</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
<lang ruby> |
<lang ruby>arr = [1,2,3,4,5] # or ary = *1..5, or ary = (1..5).to_a |
||
sum = arr.inject(0) { |sum, item| sum + item } |
|||
# => 15 |
|||
product = ary.inject(1) { |prod, element| prod * element } |
|||
# => 120</lang> |
|||
{{works with|Ruby|1.9}} |
{{works with|Ruby|1.9}} |
||
<lang ruby> |
<lang ruby>arr = [1,2,3,4,5] |
||
sum = arr.inject(0, :+) |
|||
# => 15 |
|||
product = arr.inject(1, :*) |
|||
# => 120</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
<lang scala>val a = Array(1,2,3,4,5) |
|||
val sum = a.foldLeft(0)(_ + _) |
|||
val product = a.foldLeft(1)(_ * _) |
|||
// (_ * _) is a shortcut for {(x,y) => x * y}</lang> |
|||
It may also be done in a classic imperative way : |
It may also be done in a classic imperative way : |
||
<lang scala>var sum = 0; val product = 1 |
|||
for (val x <- a) sum = sum + x |
|||
for (val x <- a) product = product * x</lang> |
|||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
<lang scheme>(apply + '(1 2 3 4 5)) |
|||
(apply * '(1 2 3 4 5))</lang> |
|||
A tail-recursive solution, without the n-ary operator "trick". Because Scheme supports tail call optimization, this is as space-efficient as an imperative loop. |
A tail-recursive solution, without the n-ary operator "trick". Because Scheme supports tail call optimization, this is as space-efficient as an imperative loop. |
||
<lang scheme>(define (reduce f i l) |
|||
(if (null? l) |
|||
i |
|||
(reduce f (f i (car l)) (cdr l)))) |
|||
(reduce + 0 '(1 2 3 4 5)) ;; 0 is unit for + |
|||
(reduce * 1 '(1 2 3 4 5)) ;; 1 is unit for * |
|||
(reduce + 0 '(1 2 3 4 5)) ;; 0 is unit for + |
|||
(reduce * 1 '(1 2 3 4 5)) ;; 1 is unit for *</lang> |
|||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
<lang seed7>const func integer: sumArray (in array integer: valueArray) is func |
|||
result |
|||
var integer: sum is 0; |
|||
local |
|||
var integer: value is 0; |
|||
begin |
|||
for value range valueArray do |
|||
sum +:= value; |
|||
end for; |
|||
end func; |
|||
const func integer: prodArray (in array integer: valueArray) is func |
|||
result |
|||
var integer: prod is 1; |
|||
local |
|||
var integer: value is 0; |
|||
begin |
|||
for value range valueArray do |
|||
prod *:= value; |
|||
end for; |
|||
end func; |
|||
const func integer: prodArray (in array integer: valueArray) is func |
|||
result |
|||
var integer: prod is 1; |
|||
local |
|||
var integer: value is 0; |
|||
begin |
|||
for value range valueArray do |
|||
prod *:= value; |
|||
end for; |
|||
end func;</lang> |
|||
Call these functions with: |
Call these functions with: |
||
writeln(sumArray([](1, 2, 3, 4, 5))); |
writeln(sumArray([](1, 2, 3, 4, 5))); |
||
writeln(prodArray([](1, 2, 3, 4, 5))); |
writeln(prodArray([](1, 2, 3, 4, 5))); |
||
Line 810: | Line 713: | ||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
<lang slate>#(1 2 3 4 5) reduce: [:sum :number | sum + number] |
|||
<lang slate> |
|||
#(1 2 3 4 5) reduce: [: |
#(1 2 3 4 5) reduce: [:product :number | product * number]</lang> |
||
#(1 2 3 4 5) reduce: [:product :number | product * number] |
|||
</lang> |
|||
Shorthand for the above with a macro: |
Shorthand for the above with a macro: |
||
<lang slate> |
<lang slate>#(1 2 3 4 5) reduce: #+ `er |
||
#(1 2 3 4 5) reduce: # |
#(1 2 3 4 5) reduce: #* `er</lang> |
||
#(1 2 3 4 5) reduce: #* `er |
|||
</lang> |
|||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
<lang smalltalk> |
<lang smalltalk>#(1 2 3 4 5) inject: 0 into: [:sum :number | sum + number] |
||
#(1 2 3 4 5) inject: 1 into: [:product :number | product * number]</lang> |
|||
Some implementation also provide a ''fold:'' message: |
Some implementation also provide a ''fold:'' message: |
||
<lang smalltalk>#(1 2 3 4 5) fold: [:sum :number | sum + number] |
|||
#(1 2 3 4 5) fold: [:product :number | product * number]</lang> |
|||
#(1 2 3 4 5) fold: [:product :number | product * number]</lang> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
===Arrays=== |
|||
<lang ocaml>(* ints *) |
|||
val a = Array.fromList [1, 2, 3, 4, 5]; |
|||
Array.foldl op+ 0 a; |
|||
Array.foldl op* 1 a; |
|||
(* reals *) |
|||
val a = Array.fromList [1.0, 2.0, 3.0, 4.0, 5.0]; |
|||
Array.foldl op+ 0.0 a; |
|||
Array.foldl op* 1.0 a;</lang> |
|||
===Lists=== |
|||
<lang ocaml(* ints *) |
|||
'''Lists''' |
|||
val x = [1, 2, 3, 4, 5]; |
|||
(* ints *) |
|||
foldl op+ 0 x; |
|||
val x = [1, 2, 3, 4, 5]; |
|||
foldl op* 1 x; |
|||
(* reals *) |
|||
foldl op* 1 x; |
|||
val x = [1.0, 2.0, 3.0, 4.0, 5.0]; |
|||
(* reals *) |
|||
foldl op+ 0.0 x; |
|||
val x = [1.0, 2.0, 3.0, 4.0, 5.0]; |
|||
foldl op* 1.0 x;</lang> |
|||
foldl op* 1.0 x; |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
<lang tcl>set arr [list 3 6 8] |
<lang tcl>set arr [list 3 6 8] |
||
Line 860: | Line 753: | ||
=={{header|Toka}}== |
=={{header|Toka}}== |
||
<lang toka>4 cells is-array foo |
|||
212 1 foo array.put |
|||
51 2 foo array.put |
|||
12 3 foo array.put |
|||
91 4 foo array.put |
|||
[ ( array size -- sum ) |
|||
>r 0 r> 0 [ over i swap array.get + ] countedLoop nip ] is sum-array |
|||
( product ) |
( product ) |
||
reset 1 4 0 [ i foo array.get * ] countedLoop .</lang> |
|||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|NetBSD|3.0}} |
{{works with|NetBSD|3.0}} |
||
Line 912: | Line 804: | ||
done; |
done; |
||
echo $SUM $PROD |
echo $SUM $PROD |
||
=={{header|UnixPipes}}== |
=={{header|UnixPipes}}== |
||
prod() { |
prod() { |