sorrysorrysorrysorry
sorrysorrysorrysorry

Reputation: 163

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?

Upvotes: 14

Views: 7755

Answers (2)

Pascal Cuoq
Pascal Cuoq

Reputation: 80335

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 signature constraints, 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".

Upvotes: 15

Ignacio
Ignacio

Reputation: 367

This question is old but maybe this is useful to someone:

A file named a.ml appears as a module A in the program... The interface of the module a.ml can be written in file named a.mli

slide link

This is from the OCaml MOOC from Université Paris Diderot.

Upvotes: 1

Related Questions