Home > Enterprise >  How to extract the n-th Elements of tuples inside a list in OCaml
How to extract the n-th Elements of tuples inside a list in OCaml

Time:06-06

Let tl be a list of (int * float) tuples which represent a numeration as int and the actual value as a float in each tuple as:

let tl = [ (1 , 2.3) ; (4 , 8.9) ; (10 , 3.)  ];;
val tl : (int * float) list = [(1, 2.3); (4, 8.9); (10, 3.)]

One can extract a single value as follows:

let ext(a,b) = b;;
val ext : 'a * 'b -> 'b = <fun>

ext (1 , 3.);;
- : float = 3.

Now I want to write a function which extracts and adds all of the floats inside the tuples of the list. I tried to do that with a recursive pattern-matching function but I do not understand why it doesn't work for I'm a complete beginner.

let rec sum lst = function
        [] -> 0.0
        | (a,h) :: (b,t) -> h  . sum (b,t);;

Error: This pattern matches values of type 'a * 'b
       but a pattern was expected which matches values of type ('c * 'd) list

CodePudding user response:

There are two problems with the code:

  1. sum takes an argument lst and then it returns a function. You either want to remove lst argument or replace function with match lst with.

  2. You're matching the tail of the list as a tuple instead of a list.

Fixed code:

let rec sum = function
  [] -> 0.0
  | (a, h) :: tl -> h  . sum tl;;

or, if you want to use match:

let rec sum lst = match lst with
  [] -> 0.0
  | (a, h) :: tl -> h  . sum tl;;
  • Related