-
Notifications
You must be signed in to change notification settings - Fork 5
Add a "with" syntax for patterns
Git branch: with-patterns
This project is to add a "with" syntax for pattern guards to OCaml. This has previously been implemented in the ocaml-patterns preprocessor.
A with
guard is similar to a when
guard except that instead of matching an expression against true
it can match an expression against any pattern. This also allows with guards to bind variables for use in the case's expression.
The following example calls lookup
on the matched x
and then checks that the result matches Some v
. This v
can then be used in the case expression.
match e with
Var x with Some v = lookup x env -> v
| Var x -> failwith ("Unbound variable " ^ x)
| Const v -> v
With guards can also be used with or-patterns to bind variables:
match x with
Foo(y, z)
| Bar y with z = 3 -> y + z
or similarly:
let f (Some x | None with x = 0) = x
Add a with <pattern> = <expression>
production to the parser. This should be placed wherever a when
guard is allowed. This will require adding a contructor for with guards to the parsetree.
with
guards should also be allowed on or-patterns, even though when
guards are not allowed on them . We will only allow exhaustive patterns for with
guards on or-patterns, so the reasons for not allowing when
guards on then do not apply.
Typecore is where the guards must be typechecked and translated into the typedtree.
The exhaustivity checker (parmatch.ml) should be used to check that with guards on or-patterns are exhaustive.
The actual compilation of with guards would be done in bytecomp/matching.ml. This file is complicated, and it helps to read the paper that is referenced in the comments at the top of the file.