Skip to content

Style tips

In general, we encourage you to use the ocamlformat autoformatter, as described in the "Formatting your code" page. However, here are some additional style tips in case you don't use it.

Don't use unnecessary parentheses!

Programmers not familiar with OCaml often add unnecessary parentheses. OCaml doesn't require parentheses around function arguments, so this code:

# let foo(x) = x + 1;;
# foo(4);;

should be written as:

# let foo x  = x + 1;;
# foo 4 ;;

OCaml will accept either form, but when there is more than one argument, the parentheses change the meaning:

# let foo1(x, y) = x + y;;
# let foo2 x y = x + y;;    (* different! *)

In this case, the first argument takes a 2-tuple as its sole argument, whereas the second function has two distinct arguments.

This also comes up with constructors:

# type foo = Foo of int;;
# Foo(10);;
- : foo = Foo 10
# Foo 10;;
- : foo = Foo 10

The version without parentheses is always preferred.

In general, only add parentheses when you need to. There is one exception: OCaml often allows you to omit the parentheses around a tuple value or a tuple pattern. I consider it much more readable to include them in this case:

# 1, 2, 3;;
- : int * int * int = (1, 2, 3)
# (1, 2, 3);;
- : int * int * int = (1, 2, 3)

The second form is preferred.