Search code examples
moduleocamlprivate

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

  • This isn't idiomatic, but for completion's sake:

    Since 4.08, when open was extended to accept arbitrary module expressions, it's possible to create private bindings without using module signatures:

    open struct
      let local = 2
    end
    

    Before this you'd have to give the module a name and then open it, which will expose the module with its contents, although it can of course be given a name that suggests it shouldn't be used.

    module Internal = struct
      let local = 2
    end
    
    open Internal