Search code examples
ocamlnotation

How can I define notation in OCaml?


I'm trying to define notation for a type I defined in my OCaml project. Basically this type allows me to express either one or two values of a type and I called it maybe_pair. I'd like to be able to write some notation for defining values of this type, for example:

  • For a single value we could write <5> : int maybe_pair
  • For two values we could write <3;7> : int maybe_pair

I'm basically trying to imitate how the lists notation work, but I believe this may be impossible.


Solution

  • You can't get the notation you want just by defining OCaml functions. You can define < and > as infix operators (with a fixed pre-defined precedence), but you can't define them to work in pairs like parentheses.

    You can get any desired syntax using the OCaml syntax extension mechanism ppx. But this is a large subject, too big for an answer here on StackOverflow (in my opinion).

    You can read about PPX here: https://ocamlverse.github.io/content/ppx.html

    And here: https://github.com/ocaml-ppx/ppxlib