'Private values in OCaml module?

Is is possible to have a let binding (whether a function, value etc.) that is private to its module, and not visible from outside?

Let's say we have A.ml:

let exported = 1
let local = 2

I only want exported to be accessible from other modules. B.ml:

let a = A.exported
let error = A.local (* This should error *)

Similar to what let%private does in Reason.



Solution 1:[1]

This is the motivation behind signature and mli files: they allow to hide information to the external world and expose only the relevant part of your API and not implementation details. In your case, it would look like

(* A.ml *)
let exported = 1
let local = 2

and

(* A.mli *)
val exported: int

Then only exported will be visible outside of A.ml.

Solution 2:[2]

Yes, that's what module signatures and on the file level the .mli file is for.

Briefly explained, add an A.mli, then put the definitions you want to export into it:

val exported : int

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 octachron
Solution 2 glennsl