简体   繁体   中英

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] doesn't match all possible values of its type. 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.

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] . 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. 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.


[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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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