简体   繁体   English

OCaml:如何从类型获取参数?

[英]OCaml : How to get a parameter from a type?

This is really simple but I can't find the answer to it anywhere. 这真的很简单,但我找不到任何答案。

Let's say I created a new type student = string * int which is a tuple of a student's name and his score on a test. 假设我创建了一个新type student = string * int ,它是一个学生的名字和他在测试中的分数的元组。

Then a list of student is passed to a function, and I have to find the average score of the class (or the list). 然后将学生列表传递给函数,我必须找到班级的平均分数(或列表)。

let blah (class : student list) : float =
match class with
[] -> [] 
| hd :: tl -> hd ??????

So I start a standard pattern matching, get one element of the list (aka a student) but how exactly do I extract the test score? 因此,我开始进行标准模式匹配,得到列表中的一个元素(又名学生),但是我如何准确地提取测试分数呢? I feel like it's something really obvious and elementary but I've only previously coded with ints, strings, int lists, int list list, etc.. where hd is specifically the piece of information you want. 我觉得这确实很明显而且很基础,但是我以前只用int,字符串,int列表,int列表列表等进行编码。其中hd是您想要的特定信息。

You just need a more elaborate pattern: 您只需要一个更复杂的模式:

match class with
| [] -> ...
| (name, score) :: tl -> ...

In some cases you can use fst and snd to get the components of a pair, but matching usually gives you cleaner code (in my experience). 在某些情况下,您可以使用fstsnd来获取一对组件,但根据我的经验,匹配通常可以为您提供简洁的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM