Search code examples
f#ocamlreasonrescript

Are there use cases for single case variants in Ocaml?


I've been reading F# articles and they use single case variants to create distinct incompatible types. However in Ocaml I can use private module types or abstract types to create distinct types. Is it common in Ocaml to use single case variants like in F# or Haskell?


Solution

  • For what it's worth it seems to me this wasn't particularly common in OCaml in the past.

    I've been reluctant to do this myself because it has always cost something: the representation of type t = T of int was always bigger than just the representation of an int.

    However recently (probably a few years) it's possible to declare types as unboxed, which removes this obstacle:

    type [@unboxed] t = T of int
    

    As a result I've personally been using single-constructor types much more frequently recently. There are many advantages. For me the main one is that I can have a distinct type that's independent of whether it's representation happens to be the same as another type.

    You can of course use modules to get this effect, as you say. But that is a fairly heavy solution.

    (All of this is just my opinion naturally.)