Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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#?

like image 684
kimsk Avatar asked Sep 09 '13 04:09

kimsk


1 Answers

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
like image 133
Tomas Petricek Avatar answered Nov 08 '22 09:11

Tomas Petricek