Anonymous user
Averages/Arithmetic mean: Difference between revisions
Add Mercury.
(solution in Wart) |
(Add Mercury.) |
||
Line 1,459:
print (mean #(3, 1, 4, 1, 5, 9))</lang>
=={{header|Mercury}}==
<lang mercury>:- module arithmetic_mean.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module float, list, require.
main(!IO) :-
io.print_line(mean([1.0, 2.0, 3.0, 4.0, 5.0]), !IO).
:- func mean(list(float)) = float.
mean([]) = func_error("mean: emtpy list").
mean(Ns @ [_ | _]) = foldl((+), Ns, 0.0) / float(length(Ns)).
:- end_module arithmetic_mean.</lang>
Alternatively, we could use inst subtyping to ensure we get a compilation error if the
mean function is called with an empty list.
<lang mercury>:- func mean(list(float)::in(non_empty_list)) = (float::out).
mean(Ns) = foldl((+), Ns, 0.0) / float(length(Ns)).</lang>
=={{header|МК-61/52}}==
|