Are compliance cases verified by application checked?

I have 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 the same, and in theory they should be identical if the cases are compared in a sequential order. But is this guaranteed in OCaml? What should I do if some newer version of the compiler starts optimizing compliance statements by reordering the order? In this case, only the second version will give the correct result. Should I worry about this?

+4
source share
2 answers

From Application Development with Objective Caml ;

Indeed, the form function p1 โ†’ expr1 | ... | pn โ†’ exprn
equivalent to function expr โ†’ matching expr with p1 โ†’ expr1 | ... | pn โ†’ exprn

and the note on match has this to say:

match expression with | p1 โ†’ expr1
:
| pn โ†’ exprn

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

No, this is part of the language, and you do not need to worry.

+4
source

Yes, the order will not change.

Many possible patterns will not work at all if the order is not defined - any patterns where later cases are more general than the previous ones break. In my experience, quite a few templates take this form. The optimizer simply cannot do this, because the gigantic strips of code will break very thinly.

manual this explicitly indicates:

If multiple patterns match expr, select the one that occurs first in the match expression.

+2
source

All Articles