2
votes

I get a warning for this function :

let dayofW' (d:System.DateTime) =
  match d.DayOfWeek with
  | DayOfWeek.Sunday    -> 0.0
  | DayOfWeek.Monday    -> 1.0
  | DayOfWeek.Tuesday   -> 2.0
  | DayOfWeek.Wednesday -> 3.0
  | DayOfWeek.Thursday  -> 4.0
  | DayOfWeek.Friday    -> 5.0
  | DayOfWeek.Saturday  -> 6.0

Incomplete pattern matches on this expression. For example, the value 'enum (7)' may indicate a case not covered by the pattern(s).

I understand that I have to deal with Enum (and not DU) but I can't find a way. I could not find an "Enum pattern" in msdn language reference.

How could I remove the warning with the minimum overwork?

2

2 Answers

6
votes

The problem is, .NET enums aren't "strong". For example,

(DayOfWeek)42

is a perfectly valid value of the DayOfWeek enum.

This means that you must handle the other possible values as well, not only the "named" ones. Now, of course, (DayOfWeek)42 shouldn't ever appear anywhere, so the proper response to a value like that could be an exception or some error value. But you still have to add it as another pattern:

| _ -> WhateverErrorValue
5
votes

Simplest way would be adding the ignoring pattern at the end:

let dayofW' (d:System.DateTime) =
  match d.DayOfWeek with
  | DayOfWeek.Sunday    -> 0.0
  | DayOfWeek.Monday    -> 1.0
  | DayOfWeek.Tuesday   -> 2.0
  | DayOfWeek.Wednesday -> 3.0
  | DayOfWeek.Thursday  -> 4.0
  | DayOfWeek.Friday    -> 5.0
  | DayOfWeek.Saturday  -> 6.0
  | _ -> 0.0 //Or throw an error, depends on how you wanna deal with this

It happens because even though you are listing every possible combination of the DayOfWeekenum, any numeric value can be casted to become an enum, so in theory d.DayOfWeek could have a value that is not listed in your pattern.