Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition of element in a list of record (OCaml)

Tags:

list

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.

like image 447
moumoute6919 Avatar asked Jan 13 '23 04:01

moumoute6919


2 Answers

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.

like image 169
Charles Marsh Avatar answered Jan 22 '23 01:01

Charles Marsh


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.

like image 41
Thomash Avatar answered Jan 22 '23 00:01

Thomash