Are match cases guaranteed to be tested by declaration order?

ocaml

Solution

From Developing Applications with Objective Caml;

In fact the form function p1 -> expr1 | ...| pn -> exprn is equivalent to function expr -> match expr with p1 -> expr1 | ...| pn -> exprn

and the note on `match` has this to say;

match expr with | p1 -> expr1 : | pn -> exprn

The expression expr is matched sequentially to the various patterns p1, ..., pn.

So no, this is a part of the language, and you don't need to worry.

Problem

I have these two functions: ``` let print_length = function | [] -> Printf.printf "The list is empty" | xs -> Printf.printf "The list has %d elements" (List.length xs) let print_length = function | [] -> Printf.printf "The list is empty" | (_ :: _) as xs -> Printf.printf "The list has %d elements" (List.length xs) ``` In practice they behave identically, and in theory they should be identical as long as the cases are matched in sequential order. But is this guaranteed in OCaml? What if the some newer version of the compiler starts optimizing match statements by rearranging the order? In that case, only the second version would produce the correct result. Should I be worrying about this?

Original source