F# Incomplete pattern matches on this expression when using "when"..Why?

5.2k views Asked by At

I have this simple F# function:

let compareNum x =
    let y = 10
    match x with
    | _ when x = y -> 0
    | _ when x > y -> 1
    | _ when x < y -> -1

However, F# compiler gives me "Incomplete pattern matches on this expression" warning. In this case, all cases should cover every pattern.

I also see a similar example in "Pattern Matching" section in the 1st edition of Programming F# book by Chris Smith. So something might be changed in the later version of F#?

1

There are 1 answers

1
Tomas Petricek On BEST ANSWER

I think the answer to the previous question (and the comments -- "In general, it is an anti-pattern to have a when guard in the last pattern" -- by kimsk) explain the situation.

However, I would not say that having a guard in the last pattern is an anti-pattern - it is the easiest workaround, but I find this somewhat unfortunate, because the when pattern gives you useful information about the values you can expect - and that makes understanding the program easier. Last time I had this problem, I left it there, at least as a comment:

let compareNum x =
  let y = 10
  match x with
  | _ when x = y -> 0
  | _ when x > y -> 1
  | _ (*when x < y*) -> -1