NEXT ·  UP ·  PREVIOUS ·  CONTENTS ·  INDEX

Signature matching

There is a final point to be made about the interaction between the type information supplied in a signature and the type information inferred from the body of a structure. The body of a structure must be well-typed in isolation from the signature constraint. Casually speaking, we could phrase this as ``the signature goes on last''. Consider the following example of an integer cell which must initially be assigned a value before that value can be inspected. [This is a little different from the built-in integer reference cells of Standard ML because these must always be assigned an initial value at the point of declaration and never raise exceptions during use.] We might decide to use an integer list with the empty list indicating that no value has been assigned.

(* Rejected due to failure to type-check *)

signature Cell =
sig
   val assign : int -> unit
   exception Inspect
   val inspect : unit -> int
end;

structure Cell :> Cell =
struct
   val c = ref []
   fun assign x = c := [x]
   exception Inspect
   fun inspect () = List.hd (!c)
       handle Empty => raise Inspect
end;

This structure declaration will not compile. The reason for this is that the structure body must compile in isolation from the signature constraint and in this case it cannot do this because the reference value c is a reference to a polymorphic object. In order to repair this mistake we must give a type constraint for c as shown below.

val c : int list ref = ref []

Value polymorphism is not the only aspect of the language which allows us to observe that the signature goes on last. The same effect can be observed via default overloading.

signature WordSum =
sig
   val sum : word * word -> word
end;

structure WordSum :> WordSum =
struct
  val sum = op +
end;

Here the difference is that the structure body is well-typed but does not match the signature. The solution is the same: introduce a type constraint in the structure body.

NEXT ·  UP ·  PREVIOUS ·  CONTENTS ·  INDEX