简体   繁体   English

警告意味着什么?

[英]What does the warning mean?

# let [x;y;z] = [1;2;3];;
Warning P: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
[]
val x : int = 1
val y : int = 2
val z : int = 3
# x;;
- : int = 1
# y;;
- : int = 2
# z;;
- : int = 3

It seems the value declaration works quite well, what is the warning actually trying to tell? 似乎价值宣言运作得很好,实际上要告诉的警告是什么?

The pattern [x; y; z] 模式[x; y; z] [x; y; z] [x; y; z] doesn't match all possible values of its type. [x; y; z]不匹配其类型的所有可能值。 In general, you want to avoid patterns like this--it means there are cases where your code will fail. 通常,您希望避免这样的模式 - 这意味着您的代码会出现故障。 In this particular case (if you never change the code) there's no problem because the pattern is matched against a constant value. 在这种特殊情况下(如果您从未更改过代码),没有问题,因为模式与常量值匹配。 But the compiler is warning you anyway, just in case. 但是为了以防万一,编译器仍在警告你。 Perhaps it figures you might change the constant list later. 也许它认为您可能会在以后更改常量列表。

It would be nice to have a way to disable the warning for cases like this, I have to say. 我不得不说,有一种方法可以禁用这种情况的警告。

The idiomatic way to write this (with no warning) is: 写这个(没有警告)的惯用方法是:

let x, y, z = 1, 2, 3

In this case, the pattern ( x, y, z ) does match all possible values of its type. 在这种情况下,模式( x, y, z确实匹配其类型的所有可能值。

Basically, any expression binding is translated at compile time into a pattern match, since it is possible to wrie a pattern on the left side of the binding sign = . 基本上,任何表达式绑定在编译时都会转换为模式匹配,因为可以在绑定符号=的左侧绘制模式。 So it's pretty much as if you wrote: 所以它就像你写的那样:

let x,y,z = 
    let v =  [1;2;3] in
    match v with
      | [x;y;z] -> x,y,z

This a bit convoluted, but the code which is typechecked could resemble a little to the above [1] . 这有点复杂,但是typechecked的代码可能与上面的内容相似[1] In this setting, you can see perhaps a bit better that the pattern matching mechanism is the same whether you use a simple binding expression or a full fledged match ... with expression. 在这个设置中,无论你使用简单的绑定表达式还是完全成熟的match ... with表达式,你都可以看到模式匹配机制相同的好一点。 In both cases, the typechecker will infer from the type of the expression if there are cases which are missed by the pattern match, and warn you about them. 在这两种情况下,类型检查器都会根据表达式的类型推断出是否存在模式匹配错过的情况,并向您发出警告。 For list pattern matches, indeed the value [] is a possibility. 对于list模式匹配,确实值[]是可能的。


[1]: I say "could" , because I believe that actually the match ... with syntactic form is also transformed to another form, which is probably closer to the function form (ie. function [x;y;z] -> ... in your case). [1]:我说“可能”,因为我相信实际上match ... with句法形式也转换为另一种形式,这可能更接近function形式(即function [x;y;z] -> ...在你的情况下)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM