What is the conventional way to create an interface in OCaml? It’s possible to have an interface with a single implementation by creating an interface file foo.mli and an implementation file foo.ml, but how can you create multiple implementations for the same interface?
What is the conventional way to create an interface in OCaml? It’s possible to
Share
If you’re going to have multiple implementations for the same signature, define your signature inside a compilation unit, rather than as a compilation unit, and (if needed) similarly for the modules. There’s an example of that in the standard library: the
OrderedTypesignature, that describes modules with a type and a comparison function on that type:This signature is defined in both
set.mliandmap.mli(you can refer to it as eitherSet.OrderedTypeorMap.OrderedType, or even write it out yourself: signatures are structural). There are several compilation units in the standard library that have this signature (String,Nativeint, etc.). You can also define your own module, and you don’t need to do anything special when defining the module: as long as it has a type calledtand a value calledcompareof typet -> t -> int, the module has that signature. There’s a slightly elaborate example of that in the standard library: theSet.Makefunctor builds a module which has the signatureOrderedType, so you can build sets of sets that way.