0
votes

I recently made a mistake with OCaml pattern matching, the basic idea is the following:

utop # module X = struct let x = 10 end;;
module X : sig val x : int end     

utop # match 10 with 
| X.x -> x
| _ -> 0;;
Error: Parse error: [module_longident] expected after "." (in [module_longident])

Now, I know in retrospect the mistake I am making: the variable names used within the pattern are going to be bound if the pattern matches. They are not going to be used as constants to match even if they are.

However, the error message threw me off completely. If I weren't using x as part of a module, I would get instead a more understandable message:

utop # let x = 20;;
val x : int = 20

utop # match 10 with 
| x -> x
| _ -> 0;;
Characters 26-27:
Warning 11: this match case is unused.
- : int = 10

In this second example I understand the error message: that | x -> will match everything, so the | _ -> is redundant, so I recall I am using pattern matching incorrectly.

My question is: can someone explain to me the error message for the first example?

1

1 Answers

2
votes

If you look at the definition of a pattern in Section 6.6 of the OCaml manual, the only place a module name can appear (as far as I can see) is in this rule:

constr pattern

In other words, if you give a module name, the syntax requires a constructor from the other module. You could have a sub-module within the module, but eventually you need a constructor name. Constructor names start with an upper case letter, but your identifier starts with a lower case letter. This (however unsatisfying) is what the error message is trying to tell you (I think).