I have a list of the form (int * float) list
So, as far as I understand it (Im 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.
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)]
my_map (fun (i, _) -> i) [(3, 1.0); (4, 2.0); (6, 0.1)]
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.