26 Static Checking of Pattern Matching

There can be more to static semantics than type checking.

See that warning? That's because we're missing anything match with a non empty list. What happens if our pattern doesn't match?

Uh oh! That's a bad exception!

We can fix our empty function by making our matching exhaustive:

What about this code?

Our match case [x] is unused! But why? [x] can also be written as x :: [] (pronounced "x cons nils"), so it will always match the first pattern before the second.

In this case, as shown above, our code still works, but it's ugly :(. We should fix this:

There! No error, and our code is prettier!

What's happening here? Well, the functions List.hd and List.tl return the head and tail of a list; however, there's no head and tail of an empty list so these functions throw an exception. Here, the programmer forgets that the list might be empty. This is why it's dangerous to use List.hd and List.tl, and better as a practice to use pattern matching.

Static checking helps us write better code.

The OCaml compiler checks for, in addition to type correctness,

This is another example of static semantics.

Do not ignore these warnings The compiler is finding errors for you and giving you a chance to fix them!