Averages/Arithmetic mean: Difference between revisions
Content added Content deleted
m (→{{header|Fortran}}: langtag) |
(added standard ml) |
||
Line 439: | Line 439: | ||
> (mean (list 3 1 4 1 5 9)) |
> (mean (list 3 1 4 1 5 9)) |
||
3 5/6 |
3 5/6 |
||
=={{header|Standard ML}}== |
|||
These functions return a real: |
|||
<lang sml>fun mean_reals [] = 0.0 |
|||
| mean_reals xs = foldl op+ 0.0 xs / real (length xs); |
|||
val mean_ints = mean_reals o (map real);</lang> |
|||
the previous code is easier to read and understand, though if you which |
|||
the fastest implementation to use in production code notice several points: |
|||
it is possible to save a call to <code>length</code> computing the length through |
|||
the <code>foldl</code>, and for mean_ints it is possible to save calling |
|||
<code>real</code> on every numbers, converting only the result of the addition. |
|||
Also the task asks to return 0 on empty lists, but in Standard ML this case |
|||
would rather be handled by an exception. |
|||
<lang sml>fun mean_reals [] = raise Empty |
|||
| mean_reals xs = let |
|||
val (total, length) = |
|||
foldl |
|||
(fn (x, (tot,len)) => (x + tot, len + 1.0)) |
|||
(0.0, 0.0) xs |
|||
in |
|||
(total / length) |
|||
end; |
|||
fun mean_ints [] = raise Empty |
|||
| mean_ints xs = let |
|||
val (total, length) = |
|||
foldl |
|||
(fn (x, (tot,len)) => (x + tot, len + 1.0)) |
|||
(0, 0.0) xs |
|||
in |
|||
(real total / length) |
|||
end; |
|||
</lang> |
|||
=={{header|UnixPipes}}== |
=={{header|UnixPipes}}== |