MLton 20100608 TypeVariableScope
Home  Index  
In Standard ML, every type variable is scoped (or bound) at a particular point in the program. A type variable can be either implicitly scoped or explicitly scoped. For example, 'a is implicitly scoped in
val id: 'a -> 'a = fn x => x

and is implicitly scoped in

val id = fn x: 'a => x

On the other hand, 'a is explicitly scoped in

val 'a id: 'a -> 'a = fn x => x

and is explicitly scoped in

val 'a id = fn x: 'a => x

A type variable can be scoped at a val or fun declaration. An SML type checker performs scope inference on each top-level declaration to determine the scope of each implicitly scoped type variable. After scope inference, every type variable is scoped at exactly one enclosing val or fun declaration. Scope inference shows that the first and second example above are equivalent to the third and fourth example, respectively.

Section 4.6 of the Definition specifies precisely the scope of an implicitly scoped type variable. A free occurrence of a type variable 'a in a declaration d is said to be unguarded in d if 'a is not part of a smaller declaration. A type variable 'a is implicitly scoped at d if 'a is unguarded in d and 'a does not occur unguarded in any declaration containing d.

Scope inference examples

Restrictions on type variable scope

It is not allowed to scope a type variable within a declaration in which it is already in scope (see the last restriction listed on page 9 of the Definition). For example, the following program is invalid.

fun 'a f (x: 'a) =
   let
      fun 'a g (y: 'a) = y
   in
      ()
   end

MLton reports

Error: z.sml 3.11.
  Type variable 'a scoped at an outer declaration.

This is an error even if the scoping is implicit. That is, the following program is invalid as well.

fun f (x: 'a) =
   let
      fun 'a g (y: 'a) = y
   in
      ()
   end


Last edited on 2005-12-02 03:01:09 by StephenWeeks.