Using foldl to get the mean of a list

33 Views Asked by At

I am trying to get the mean of a list by using the following helping function:

let rec foldl f l b = match l with
  | [] -> b
  | x :: l -> foldl f l (f x b);;

let avg l = foldl (fun x acc -> let x = (a,b) in avv = (a +. acc) /. (b + 1)) l 0;;

But it keeps giving me errors after error

Need a corrected version of it

1

There are 1 best solutions below

0
Luatic On

One simple way to implement a correct average is to implement it in terms of sum and len(gth), both of which are straightforward to write in terms of foldl:

let sum l = foldl (+.) l 0.0
let len l = foldl (fun _ n -> n + 1) l 0
let avg l = sum l /. float_of_int (len l)

(we could also make len l return a float by using +., 1.0 and 0.0 instead of casting using float_of_int, but that wouldn't make much sense)

You seem to have tried to keep track of both the current length and the current sum at the same time, using a tuple, so let's do that too:

let avg l = 
  let (sum, len) = foldl (fun x (s, n) -> (s +. x, n +. 1.0)) l (0.0, 0.0) in 
  sum /. len