Reputation: 122412
I'm trying to find the average of a list of floats.
let avg l =
List.fold_left ( +. ) 0 l /. List.length l;;
How does List.fold_left work? (Applies the first argument to a list (the third arg)... but then what is the second argument?)
Toplevel returns this error:
Characters 43-44:
List.fold_left ( +. ) 0 l /. List.length l;;
^
Error: This expression has type int but is here used with type float
What is the preferred way to iterate through a list in OCaml?
Upvotes: 3
Views: 6945
Reputation: 122429
As Chuck mentioned, there is no automatic conversion between ints and floats. Also, to be a float literal it must have either a decimal point or be in exponential notation.
So to fix your code, you need to add a decimal point to the 0 to make it a float constant; and you also need to convert the length from an int to a float:
let avg l =
List.fold_left ( +. ) 0. l /. float_of_int (List.length l);;
Upvotes: 5
Reputation: 237010
The second argument is the initial value of the accumulator. For a left fold, you can visually place it to the left of the list. So for a left fold on [1;2;3;4;5]
with an initial value of 0, it works out to:
((((0 + 1) + 2) + 3) + 4) + 5
So in this case, the innermost parenthesis works out to (0 +. 1.0)
, which won't work in OCaml because 0 is an int and the language doesn't automatically convert it to a float for you.
Upvotes: 8