user5357314
user5357314

Reputation: 31

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.

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.

Upvotes: 1

Views: 510

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

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).

Upvotes: 4

Related Questions