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 that declaring a value works really well, what is the warning to actually trying to say?

+3


source to share


2 answers


The pattern [x; y; z]

does not match all possible values ​​of its type. In general, you want to avoid patterns like this - this means that there are cases where your code will not work. In this particular case (if you never change the code) there is no problem, because the pattern is matched against a constant value. But the compiler warns you anyway, just in case. Perhaps this may affect the change of the list of constants later.

It would be nice to have a way to turn off the warning for cases like this, I must say.

Idiomatic way to write this (without warning):



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

      

In this case, the pattern ( x, y, z

) matches all possible values ​​of its type.

+5


source


Basically, the expression binding binds at compile time to pattern matching, since it is possible to draw a pattern on the left side of the anchor mark =

. So it is 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 is a bit confusing, but the code that is typechecked might look a little like the above [1] . In this setting, you can see, perhaps slightly better, that the pattern matching mechanism is the same whether you use a simple binding expression or a full expression match ... with

. In both cases, typechecker will infer from the expression type if there are cases that were missed by the pattern match and warn you about them. To match the pattern list

, a value is indeed possible []

.




[1]: I say "may" because I believe that in fact the syntactic form is match ... with

also converted to another form, which is probably closer to the form function

(ie function [x;y;z] -> ...

in your case).

0


source







All Articles