OCaml: How does List.fold_left work?

I am trying to find the average from 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 the list (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 over a list in OCaml?

+3
source share
2 answers

The second argument is the initial value of the battery. For the left fold, you can visually place it to the left of the list. So, for the left fold on [1;2;3;4;5]with an initial value of 0, it works:

((((0 + 1) + 2) + 3) + 4) + 5

, (0 +. 1.0), OCaml, 0 int, float .

+8

, int float . , , , .

, , 0, ; int float:

let avg l =
    List.fold_left ( +. ) 0. l /. float_of_int (List.length l);;
+5

Source: https://habr.com/ru/post/1716979/


All Articles