Jump to content

Averages/Arithmetic mean: Difference between revisions

m (Moved to Arith cat)
Line 257:
These functions return a float:
 
<ocaml>let mean_floats xs =
if xs = [] then
0.
else
List.fold_left (+.) 0. xs /. float_of_int (List.length xs)
 
let mean_ints xs = mean_floats (List.map float_of_int xs)</ocaml>
 
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 List.length computing the length through
the List.fold_left, and for mean_ints it is possible to save calling
float_of_int on every numbers, converting only the result of the addition.
(also when using List.map and the order is not important, you can use
List.rev_map instead to save an internal List.rev.)
Also the task asks to return 0 on empty lists, but in OCaml this case
would rather be handled by an exception.
 
<ocaml>let mean_floats xs =
if xs = [] then
invalid_arg "empty list"
else
let total, length =
List.fold_left
(fun (tot,len) x -> (x +. tot), len +. 1.)
(0., 0.) xs
in
(total /. length)
;;
 
 
let mean_ints xs =
if xs = [] then
invalid_arg "empty list"
else
let total, length =
List.fold_left
(fun (tot,len) x -> (x + tot), len +. 1.)
(0, 0.) xs
in
(float total /. length)
;;</ocaml>
 
=={{header|Perl}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.