Averages/Arithmetic mean: Difference between revisions
Content added Content deleted
m (Added works with template, removed whitespace) |
(added D code) |
||
Line 84: | Line 84: | ||
0 |
0 |
||
(/ (reduce #'+ sequence) length)))) |
(/ (reduce #'+ sequence) length)))) |
||
=={{header|D}}== |
|||
Using template to make the mean function work for higher-rank array. |
|||
<pre>module mean ; |
|||
import std.stdio ; |
|||
real mean(T)(T[] a) { |
|||
static if(is(T U : U[])) { |
|||
// recursively unfold the multi-array |
|||
T u ; |
|||
foreach(e ; a) |
|||
u ~= e ; |
|||
return u.mean() ; |
|||
} else { |
|||
// do the math |
|||
if(a.length == 0) return 0.0 ; |
|||
real sum = 0.0 ; |
|||
foreach(e ; a) |
|||
sum += e ; |
|||
return sum / a.length ; |
|||
} |
|||
} |
|||
void main() { |
|||
int[] array = [3,1,4,1,5,9]; |
|||
real[][][] |
|||
multi = [[[1,2,2],[2,3,4],[4,5,7]], |
|||
[[4,1,3],[0,3,1],[4,4,6]], |
|||
[[1,3,3],[2,7,8],[9,1,5]]] ; |
|||
writefln("array : ", array.mean()) ; |
|||
writefln("multi : ", multi.mean()) ; |
|||
}</pre> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
: fmean ( addr n -- f ) |
: fmean ( addr n -- f ) |