Construct with user types safely with capital letter

module Probability : sig
    type probability = private Pr of float
    val create : float -> probability
end = struct
    type probability = Pr of float
    let create x = assert (1.0 >= x && x >= 0.0); Pr x
end

pr = Probability.create is not nice, as I construct a tree by let cT = Leaf 0.3 with capital L for example. For consistency I want let p = Pr 0.3.

I don’t know if that is even possible. Private types page wasn’t helpful. Am I following the wrong coding practices?

The best thing I could think of is

module Pr = struct
    include Probability
    let c = Probability.create
end

Then we can use Pr.c. Any better alternatives?

One approach is to use an underscore prefix for the name of “smart constructor” functions. So e.g. in the OP you could rename create to _Pr.

I personally don’t like to prefix values with an underscore because the compiler treats those specially, and they don’t trigger warnings when unused. Another option that some libraries use is v (for “value”) instead of c as their main constructor function.

The short answer to your question is no, you can’t name a value beginning with a capital letter. If you simply want everything that constructs a value to look the same, then your best option is in the other direction: add functions for your other variant constructors and use those. Then all of your constructors will be consistently lowercase.

(However, I think it’s easier to just embrace the fact that different OCaml values are constructed with different syntaxes instead of trying to make them all the same.)

2 Likes