Home > Blockchain >  Access float in (int * float) list in OCaml
Access float in (int * float) list in OCaml

Time:11-28

I have a list of type (int * float) list.

So, as far as I understand it (I'm new to OCaml/Functional Programming) the list is structured like this: [(3, 1.0); (4, 2.0); (6, 0.1)].

Now I want to access the first element in each tuple in the list.

I'd be happy with an example solution and an explanation.

CodePudding user response:

The suggestion from @glennsl in the comments about learning resources is spot on.

If you want an example of getting a list comprised of the first element in each tuple:

List.map (fun (i, _) -> i) [(3, 1.0); (4, 2.0); (6, 0.1)]

List.map applies a function to each element in a list and builds a list of the resulting values. It's a simple concept and easy enough to implement in a few lines.

let rec my_map f lst =
  match lst with
  | [] -> []
  | first::rest -> f first :: my_map f rest

Or more tersely using function:

let rec my_map f =
  function
  | [] -> []
  | first::rest -> f first :: my_map f rest

If we evaluated my_map (fun (i, _) -> i) [(3, 1.0); (4, 2.0); (6, 0.1)] it would work out something like:

my_map (fun (i, _) -> i) [(3, 1.0); (4, 2.0); (6, 0.1)]
3 :: my_map (fun (i, _) -> i) [(4, 2.0); (6, 0.1)]
3 :: 4 :: my_map (fun (i, _) -> i) [(6, 0.1)]
3 :: 4 :: 6 :: my_map (fun (i, _) -> i) []
3 :: 4 :: 6 :: []
[3; 4; 6]

The anonymous function fun (i, _) -> i is one which takes a tuple of two items and returns the first. The second is unimportant to us, so we use _ rather than giving it a name.

  • Related