当使用“何时"时,F#不完整模式与此表达式匹配.为什么? [英] F# Incomplete pattern matches on this expression when using "when"..Why?
问题描述
我有这个简单的F#函数:
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
但是,F#编译器给我此表达式上的模式匹配不完整"警告.在这种情况下,所有情况都应涵盖所有模式.
However, F# compiler gives me "Incomplete pattern matches on this expression" warning. In this case, all cases should cover every pattern.
在Chris Smith的《 Programming F#》第一版中的模式匹配"部分中,我也看到了类似的示例.因此,在更高版本的F#中可能会有所更改吗?
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#?
推荐答案
我认为评论-通常,在最后一个模式中设置警惕是一种反模式" - by
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.
但是,我不会说在最后一个模式中有一个守卫是一个反模式-这是最简单的解决方法,但是我发现这有点不幸,因为when
模式提供了您将获得有关您可以期望的值的有用信息-从而使对该程序的理解更加容易.上次遇到此问题时,我至少把它留在了那里,至少是作为评论:
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
这篇关于当使用“何时"时,F#不完整模式与此表达式匹配.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!