Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
F# F“使用”时,此表达式上的不完整模式匹配;“当”;。。为什么?_F#_Pattern Matching_Guard Clause - Fatal编程技术网

F# F“使用”时,此表达式上的不完整模式匹配;“当”;。。为什么?

F# F“使用”时,此表达式上的不完整模式匹配;“当”;。。为什么?,f#,pattern-matching,guard-clause,F#,Pattern Matching,Guard Clause,我有一个简单的F#函数: let compareNum x = let y = 10 match x with | _ when x = y -> 0 | _ when x > y -> 1 | _ when x < y -> -1 让我们比较枚举x= 设y=10 将x与 |当x=y->0时 |当x>y->1时 |_ux-1时 然而,F#编译器给了我“此表达式上的模式匹配不完整”的警告。在这种情况下,所有案例都应涵盖每种模

我有一个简单的F#函数:

let compareNum x =
    let y = 10
    match x with
    | _ when x = y -> 0
    | _ when x > y -> 1
    | _ when x < y -> -1
让我们比较枚举x=
设y=10
将x与
|当x=y->0时
|当x>y->1时
|_ux-1时
然而,F#编译器给了我“此表达式上的模式匹配不完整”的警告。在这种情况下,所有案例都应涵盖每种模式

在Chris Smith编写的第一版编程F#book中的“模式匹配”部分,我也看到了类似的例子。因此,在F#?

的更高版本中可能会有一些变化,我认为(以及--“一般来说,在最后一个模式中使用when-guard是一种反模式”)的答案解释了这种情况

但是,我不会说在最后一个模式中使用一个防护是一种反模式——这是最简单的解决方法,但我觉得这有点不幸,因为
when
模式提供了有关预期值的有用信息——这使理解程序变得更容易。上次我遇到这个问题时,我把它放在那里,至少作为一个评论:

let compareNum x =
  let y = 10
  match x with
  | _ when x = y -> 0
  | _ when x > y -> 1
  | _ (*when x < y*) -> -1
让我们比较枚举x=
设y=10
将x与
|当x=y->0时
|当x>y->1时
|_(*当x-1

编译器假定当保护时,任何带有
的代码都是不完全匹配的。这是不雅的,并产生误报,就像你看到的。可能重复感谢!我喜欢上面问题中的一个答案是这样说的:“一般来说,在最后一个模式中使用when-guard是一种反模式。”我认为这现在是有意义的。在这种情况下,使用“if”不仅更加惯用,而且是编写测试代码的一种更好的方法。谢谢!这真是一个很好的建议。+1,如果您将相等性检查
->0
作为最终模式,它可能会在某种程度上保持可读性,而无需注释,但我个人认为我更喜欢它。