4

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.

moumoute6919
  • 2,406
  • 1
  • 14
  • 17

2 Answers2

6

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.

Charles Marsh
  • 1,877
  • 16
  • 21
3

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.

Thomash
  • 6,339
  • 1
  • 30
  • 50