SML# - Resources/ProgrammingExamples/Variants Diff

  • Added parts are displayed like this.
  • Deleted parts are displayed like this.

It has been sometimes asked whether SML# support polymorphic variants, as proposed and
implemented in OCaml (really?).

In response to this question, let us note that the type theoretical basis and a
type-directed compilation method for polymorphic variants in an ML-style
language has been
proposed in the paper [["A polymorphic record calculus and its compilation. ACM TOPLAS, 17(6):844-895"|]]
(a preliminary version appeared in POPL'92) on which our SML# record polymorphism is based.

As shown in the above paper, there is no technical difficulty in implementing
labeled polymorphic variants.
The rationale behind our not introducing polymorphic variants to SML# is two-fold:
# the introduction makes it difficult to maintain the compatibility with the Definition of Standard ML.
# the main features of polymorphic variants are representable by polymorphic records.

To understand the second point, one can regard a polymorphic variant
of the form <Age = 21> as a function
fn M => #Age M 21
which takes a ''method suit'' as an argument M, and dispatches the "Age" method
on it with the value 21.
From this code, SML# compiler infers the following type:
val it = fn : ['a#{Age:int -> 'b},'b.'a -> 'b]
indicating the property that this object takes any record of methods
that contains an "Age" field of type "int -> 'b" for some result type "'b".
This type can be regarded as a polymoprhic variant type of the form:

Here is:
* [[a sample source code|VariantSource]] demonstrating this idea, and
* its [[execution results in SML#:|VaraintResult]].