Reputation: 31
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
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