4

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?

Jon Smark
  • 2,528
  • 24
  • 31

2 Answers2

5

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.

Community
  • 1
  • 1
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
2

Yes, the order is not going to change.

Many possible patterns would not work at all if the order was not defined--any patterns where later cases are more general than earlier ones would break. In my experience, quite a few patterns take this form. This simply cannot be done by the optimizer because gigantic swaths of code would break in very subtle ways.

The manual notes this explicitly:

If several patterns match the value of expr, the one that occurs first in the match expression is selected.

Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214
  • Thanks for the prompt answer. But why do you start with a definitive "No", if your answer is actually "Yes"? – Jon Smark Apr 30 '13 at 18:36
  • @JonSmark: Sorry, for some reason I read your question as "should I worry about the order changing". Looking back at it, I'm not sure why I took it that way :P. I'll edit it to clear everything up. – Tikhon Jelvis Apr 30 '13 at 18:45