Constant parameters in OCaml?

In OCaml, the read-only or write-only quality of a value is encoded as part of its type. Typically a read-only type would not expose any mutation operations and a write-only type would not expose any access operations.

In imperative languages, all data is mutable, and read-only, write-only annotations are used to restrict this mutability locally. In OCaml, almost all data is immutable, and only mutable record fields and arrays (+ its friends: byte arrays, flat float arrays, big arrays) can be mutated. The amount of mutable data in a typical OCaml program is thus much less than in your typical program written in an imperative language, so these kind of annotations are not as relevant.

As already mentioned in @zbaylin’s response, if you want a restrict the mutability of a type, you can do this typically by introducing a separate type that does not expose the operations that you want to restrict (eg writing or reading operations), but the simplest is not to use mutable data to begin with. If you must must use mutable data, you can either clearly specify your invariants (“trust it”), or introduce a suitable type to restrict the operations possible with it.

Incidentally, for the case of arrays, the addition of immutable arrays is being discussed upstream: Immutable arrays by OlivierNicole · Pull Request #13097 · ocaml/ocaml · GitHub.

Cheers,
Nicolas

9 Likes