[英]Access float in (int * float) list in Ocaml
I have a list of the form (int * float) list
我有一个表单列表
(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)]
因此,据我了解(我是 Ocaml/函数式编程的新手),列表的结构如下:
[(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. List.map
将 function 应用于列表中的每个元素并构建结果值的列表。 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
:或者更简洁地使用
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)]
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)]
它会得出如下结果:
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.匿名 function
fun (i, _) -> i
是一个接受两个项目的元组并返回第一个项目。 The second is unimportant to us, so we use _
rather than giving it a name.第二个对我们来说并不重要,所以我们使用
_
而不是给它一个名字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.