ocaml

ocaml begin/end pattern matching


Haven't been able to find much online documentation regarding begin/end in ocaml. I have two different pattern matches in the same function (which I want to be independent of each other), but vscode is parsing them to nest the second inside the first. I've tried surrounding the first pattern match in begin/end, but it's giving me syntax errors:

    begin match c.r with (* first pattern match *)
    | [ r1; r2; r3 ] -> 
        let _ = print_endline (String.make 1 r3.top) in end
    match cl with (* second pattern match *)
    | [] -> []

I get a red underline on end that says Syntax error after unclosed begin, expecting expr. I do not understand what this means, since I wrote end to close the begin, so why is the begin unclosed? The code compiles fine without the begin/end (except that it nests the second pattern match inside the first one). Thanks.


Solution

  • In OCaml begin/end is essentially identical to open/close parentheses. Inside you should have a well-formed expression (as in pretty much any programming language).

    What you have inside your begin/end is not an expression, since it ends with in. A let expression looks like let pattern = expr1 in expr2. You are missing the second expression inside the begin/end.

    What you should do (I think) is put begin/end around the inner match like this:

    match c.r with
    | [r1; r2; r3 ] ->
        let _ = print_endline (String.make 1 r3.top) in
        begin
        match c1 with
        | [] -> []
        ...
        end
    | ...
    

    (This code doesn't make a lot of sense but I assume it's just an example.)

    As another simplification you can change let _ = a in b to a; b if a is of unit type, as it is in your code.