Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml interface vs. signature?

I'm a bit confused about interfaces vs. signatures in OCaml. From what I've read, interfaces (the .mli files) are what govern what values can be used/called by the other programs. Signature files look like they're exactly the same, except that they name it, so that you can create different implementations of the interface. For example, if I want to create a module that is similar to a set in Java:

I'd have something like this:

the set.mli file:

type 'a set
  val is_empty : 'a set -> bool
  val ....
  etc.

The signature file (setType.ml)

module type Set = sig
  type 'a set

  val is_empty : 'a set -> bool 
  val ...
  etc.
end

and then an implementation would be another .ml file, such as SpecialSet.ml, which includes a struct that defines all the values and what they do.

module SpecialSet : Set
struct
 ...

I'm a bit confused as to what exactly the "signature" does, and what purpose it serves. Isn't it acting like a sort of interface? Why is both the .mli and .ml needed? The only difference in lines I see is that it names the module.

Am I misunderstanding this, or is there something else going on here?

like image 426
sorrysorrysorrysorry Avatar asked Aug 29 '11 02:08

sorrysorrysorrysorry


1 Answers

OCaml's module system is tied into separate compilation (the pairs of .ml and .mli files). So each .ml file implicitly defines a module, each .mli file defines a signature, and if there is a corresponding .ml file that signature is applied to that module.

It is useful to have an explicit syntax to manipulate modules and interfaces to one's liking inside a .ml or .mli file. This allows type substitutions, as in S with type t = M.t. Not least is the possibility it gives to define functors, modules parameterized by one or several modules: module F (X : S) = struct ... end. All these would be impossible if the only way to define a module or signature was as a file.

I am not sure how that answers your question, but I think the answer to your question is probably "yes, it is as simple as you think, and the system of having .mli files and explicit signatures inside files is redundant on your example. Manipulating modules and signatures inside a file allows more complicated tricks in addition to these simple things".

like image 187
Pascal Cuoq Avatar answered Sep 24 '22 07:09

Pascal Cuoq