Search code examples
listocamlrecord

Addition of element in a list of record (OCaml)


I have a list of record :

list_clients = [{name = "c6"; number = 9}; {name = "c12"; number = 3}; {name = "c17"; number = 6};]

I would like to simply make the sum of all the "number" of each record.

What is the best way? I'm quite beginner with OCaml.


Solution

  • Use a fold:

    List.fold_left (fun acc nxt -> nxt.number+acc) 0 list_clients
    

    This takes every element in the list, grabs said element's 'number' field, and adds it to the total thus far, passing along the result.