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.
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.
A bit more explanation about 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]
and computes f (... (f (f a b1) b2) ...) bn
. It allows you you to easily compute the sum of the elements of a list: List.fold_left (+) 0 l
, its maximum element: List.fold_left max (List.hd l) l
or anything where you need to go through every element of the list, aggregating it with the previous result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With