OCaml Operators Cheatsheet

By Brendan Long

Originally Published on Jan 16, 2018

One of the hardest parts of learning OCaml is figuring out what the infix operators do, since they’re just a string of symbols and you can’t find them with a Google search. This is my attempt to make a cheatsheet for whenever you’re wondering what a random series of symbols means. Doing a search on this page should find basic info about any of the common OCaml operators.

Note that some libraries define their own operators, like how Jane Street’s Command.Spec defines ++, +>, and +<. In cases like that, hopefully the library you’re using will make it clear what the infix operators do.

General info about infix functions

In OCaml, a function is infix if its name starts with one of these characters:

= @ ^ ∣ & + - * / $ %

Followed by zero or more of these characters:

! $ % & * + - . / : ? @ ^ ∣ ~

When defining an infix function, you need to put () around the “name”.

For example, in utop:

# let (=<>@^|&~+-*/$%!?:.) a b =
a + b ;;
val ( =<>@^|&~+-*/$%!?:. ) : int -> int -> int = <fun>
# 1 =<>@^|&~+-*/$%!?:. 2 ;;
- : int = 3

Also, you can see the type of an infix operator in utop by again wrapping the function name in parentheses:

# (=<>@^|&~+-*/$%!?:.);;
val ( =<>@^|&~+-*/$%!?:. ) : int -> int -> int = <fun>

The official documentation for this is here, although this blog has a more accessible explanation.

Built-in infix operators

The built-in operators are defined in Pervasives:

Refer to the documentation for the magic involved in functions that work on multiple types (=, <>, <, >, etc).

Jane Street

Numbers

Jane Street generally defines arithmetic operators in modules where they make sense, so you can do things like:

Bigint.(of_int 1 + of_int 3 / of_int 5)

The documentation for this interface is under Int_intf.S_common, although most of them are defined for floating point numbers too.

Monads

Jane Street’s libraries (Core, Async, Base, etc.) consistently define infix operators under Monad_infix modules.

map and bind are documented assuming that you’re familiar with monads, and you may find this StackOverflow answer useful if you need more information.

>>= and >>| show up most commonly in Async, but they can also be used with Option, List, Result, etc.

Lwt

See the Lwt documentation.

Lwt doesn’t have Async’s >>=? or >>|? because Lwt.t can contain errors without having a separate Or_error module.