Sum and product of an array: Difference between revisions
Content added Content deleted
(→{{header|PARI/GP}}: 2.10.0) |
(→{{header|JavaScript}}: ES6) |
||
Line 1,111: | Line 1,111: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===ES5=== |
|||
<lang javascript>var array = [1, 2, 3, 4, 5], |
<lang javascript>var array = [1, 2, 3, 4, 5], |
||
sum = 0, |
sum = 0, |
||
Line 1,132: | Line 1,133: | ||
}, 1); |
}, 1); |
||
alert(sum + ' ' + prod);</lang> |
alert(sum + ' ' + prod);</lang> |
||
===ES6=== |
|||
<lang JavaScript>(() => { |
|||
'use strict'; |
|||
// sum :: (Num a) => [a] -> a |
|||
const sum = xs => xs.reduce((a, x) => a + x, 0); |
|||
// product :: (Num a) => [a] -> a |
|||
const product = xs => xs.reduce((a, x) => a * x, 1); |
|||
// TEST |
|||
// show :: a -> String |
|||
const show = x => JSON.stringify(x, null, 2); |
|||
return show( |
|||
[sum, product] |
|||
.map(f => f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) |
|||
); |
|||
})();</lang> |
|||
{{Out}} |
|||
<pre>[ |
|||
55, |
|||
3628800 |
|||
]</pre> |
|||
=={{header|jq}}== |
=={{header|jq}}== |