Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml "with" guard in pattern matching

I read about pattern guards in ocaml-patterns which shows this type of guard:

match x with
| pat with g = y -> z
| ...
| pat with g = y -> z

In OCaml 4.02 however, this does not seem to work (Syntax error: pattern expected.). So the question is: is there a workaround to achieve this kind of binding in pattern matching?

I would like to write something like this:

match something with
| value with y = f x when y > 0 -> value + y
like image 227
emiliano.bovetti Avatar asked Dec 09 '14 18:12

emiliano.bovetti


1 Answers

That's OCaml "patterns" CamlP4 syntax extension. OCaml itself does not have pattern guards and this p4 extension provided it as syntax extensions, which must be desugarred by CamlP4 preprocessor before feeding to OCaml compiler.

Unfortunately "patterns" was not ported to OCaml 4. I do not know exactly why but probably due to the high porting cost to changing OCaml internal representations. CamlP4 is very powerful but its syntax exntesions are hard to write and maintain. Actually the OCaml community is now shifting to PPX, another preprocessor framework. PPX cannot change OCaml syntax itself but things are much easier there.

Recently I wrote a PPX extension for pattern guards which works with 4.02.1: https://bitbucket.org/camlspotter/ppx_pattern_guard . Your example can be translated to:

match something with
| value when [%guard let y = f x;; y > 0] -> value + y

It looks uglier than "patterns" but in PPX we have to be within the vanilla syntax with some attributes and extensions like [%guard ...].

like image 107
camlspotter Avatar answered Oct 06 '22 01:10

camlspotter