The following code takes 2 parameters. the first is a list of triples: The triple (d,m,y) is meant to represent a date.
the second is an integer which is a month
The code is meant to count the number of occurrences of dates with that month in the list
p.s. I guess this probably looks like a homework question - it's not. It's from a course I did earlier in the year in ML and I'm trying to redo all the exercises in f#. So it's only for my benefit
let rec number_in_month (dates : (int * int * int) list, month) =
match dates with
| [] -> 0
| (_,y,_) when month = y -> 1 + number_in_month(dates.Tail, month)
| _ -> number_in_month(dates.Tail, month)
but it gives the error :
This expression was expected to have type (int * int * int) list but here has type 'a * 'b * 'c
any idea what I'm doing wrong?
Your second pattern match is trying to match a single date (_,y,_) but it is being matched against your list of dates. Try matching using (_,y,_)::_ instead.
More idiomatic would be to match using (_,y,_)::tail and to use tail instead of dates.Tail later in the expression.
The code can also be tightened up (including the fix MarkP suggested). Note the use of type inference so that the type of dates does not need to be passed
let rec number_in_month dates month =
match dates with
| [] -> 0
| (_,y,_)::tail ->
( number_in_month tail month) + (if y = month then 1 else 0)
let data = [(1,2,3);(1,2,3);(1,5,7);(1,9,2);(1,9,2);(1,9,2)]
number_in_month data 5
number_in_month data 2
http://www.tryfsharp.org/create/bradgonesurfing/datefinder.fsx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With