Adding an item to a list of records (OCaml)

I have a list of entries:

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

I would just like to make the sum of the total "number" of each record.

What is the best way? I am new to OCaml.

+4
source share
2 answers

Use the fold:

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

This takes each item in the list, captures the item’s number field and adds it to the total, going through the result.

+5
source

A few more explanations regarding Charles Marsh's answer.

List.fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a takes a function f , an element a and a list [b1; b2; ...; bn] [b1; b2; ...; bn] [b1; b2; ...; bn] and computes f (... (f (fa b1) b2) ...) bn . This allows you to easily calculate the sum of the list items: List.fold_left (+) 0 l , its maximum item: List.fold_left max (List.hd l) l or whatever you need to go through each list item, combining it with the previous one result.

+3
source

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


All Articles