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

断了今生、忘了曾经 提交于 2019-11-30 23:18:49

问题


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:


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


来源:https://stackoverflow.com/questions/18691622/f-incomplete-pattern-matches-on-this-expression-when-using-when-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!