chessguy
chessguy

Reputation: 165

Sum up the elements of a record

type MyType = {a:int; b:int};;
let test = [{a=5;b=10}; {a=10;b=100}; {a=200; b=500}; {a=100; b=2}];;

I would like to create a function which will sum up a and b in such a way it will display

Sum of a : 315
Sum of b : 612

I think I have to use a recursive function. Here is my attempt :

let my_func record =
  let adds = [] in 
  let rec add_func = match adds with
  | [] -> record.a::adds; record.b::adds
  | _ -> s + add_func(e::r)

add_func test;;

This function doesn't seem to work at all. Is there a right way to do such function?

Upvotes: 0

Views: 172

Answers (2)

Chris
Chris

Reputation: 36496

This can also be accomplished quite concisely with List.fold_left which is applicable anywhere you want to convert a list to some other value.

let my_func lst =
  let add {a=a1; b=b1} {a=a2; b=b2} = 
    {a=a1+a2; b=b1+b2} 
  in
  let zero = {a=0; b=0} in
  List.fold_left add zero lst

For your test variable, evaluation would look like:

my_func [{a=5;b=10}; {a=10;b=100}; {a=200; b=500}; {a=100; b=2}]
List.fold_left add zero [{a=5;b=10}; {a=10;b=100}; {a=200; b=500}; {a=100; b=2}]
List.fold_left add {a=5; b=10} [{a=10;b=100}; {a=200; b=500}; {a=100; b=2}]
List.fold_left add {a=15; b=110} [{a=200; b=500}; {a=100; b=2}]
List.fold_left add {a=215; b=610} [{a=100; b=2}]
List.fold_left add {a=315; b=612} []
{a=315; b=612}

Upvotes: 0

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

OK, you know exactly what you're doing, you just need one suggestion I think.

Assume your function is named sumab and returns a pair of ints. Then the key expression in your recursive function will be something like this:

| { a = ha; b = hb; } :: t ->
    let (a, b) = sumab t in (ha + a, hb + b)

Upvotes: 1

Related Questions