This is the first time I post an answer on this newsgroup, I hope I
won't say stupid things (and I know, it's a very long answer to a
> let [x;y;z]=[1;2;3];;
> Ocaml give out the following output:
> Warning: 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
> Why this pattern-matching is not exhaustive?
The reason for this error message has to do with the type system O'Caml
uses. To check the exhaustiveness of a pattern, O'Caml doesn't use the
actual value passed to the pattern because most of the time it is not
known at compile-time (and pattern matching exhaustiveness has to be
checked at compile-time to be most useful). Instead, it uses the type
of the value (which is always known at compile time). The type of your
'[1;2;3]' list is simply 'int list'. Notice that the type of the list
does not contain any information about the content (and in particular
the length) of the list. So, when the pattern matching checker looks at
your pattern, only knowing the type of the value that is matched, it
says 'hey, this list could be empty, but I need a list of length three
to match it: let's print a warning'. The reason why O'Caml prints a
warning and not an error is that in some cases (like in yours) a
non-exhaustive pattern might be correct, but it is up to the developer
to check it.
So, what can you do:
1. Live with it. Warnings in O'Caml do not mean the same as in C++
(where it basically means: forget about it, it will never run), it
simply means that the compiler is not smart enough to check whether it
is correct or not, so if you are sure it is correct: fine (or play with
the 'Match_failure' exception that will be thrown at runtime if you hit
a non matching case)
2. Maybe a list is not the right structure for you in this case: what
about a record? 'let (x,y,z) = (1,2,3)' will not produce a warning. The
O'Caml type of records specifies the length of the record and the type
of every element in it ('int*int*int' in this case), and therefore the
compiler can know whether the pattern is exhaustive or not.
3. Use another language than O'Caml that allows you to specify type
constraints or has a more complete type representation for lists (with
length). As far as I know though, this is still mostly a research
field: I don't know of any serious language available outside research
labs that does this (let me know if you do). If you want to look at
what such a language might look like, check out Hongwei Xi's thesis
'Dependent Types in Practical Programming'
introduction contains some nice ML-like examples of constrained types.
You will also notice why such extended types are not used in practice:
the developer needs to add loads of additional information to it's code
for dependant types to work.
4. Choose between 1 and 2 :-)
Voilà. I hope this helps.