SML# Document Version 4.0.0
13 SML# feature: dynamic types and typed manipulation of JSON

13.2 Reification of terms and types

In statically-typed langauges, type information is usually meta information that only the compiler manages and therefore it is not included as a data structure in the object code. The memory-level data structure of a value is also meta information depending on the type information. “Reification” is the operation that extracts such meta information to objects that the code can deal with. The SML#’s dynamic typing feature is constructed on top of the reification mechanism. The users is also allowed to access the reification mechanism and obtain type information and internal structure of values as ordinary ML datatype.

SML# provides the following functions for this purpose:

  • Dynamic.dynamicToTerm : Dynamic.void Dynamic.dyn -> Dynamic.term. This extracts the value structure of a dynamically-typed value as a term representation of the Dynamic.term type. The Dynamic.term type is an ordinary ML datatype and therefore you can analyze it by the case expression.

  • Dynamic.dynamicToTy : Dynamic.void dyn -> Dynamic.ty. This extracts the type information of a dynamically-typed value as a term representation of the Dynamic.ty type. Similarly to Dynamic.term, the Dynamic.ty type is an ordinary ML datatype.

  • Dynamic.termToDynamic : Dynamic.term -> Dynamic.void Dynamic.dyn. This constructs a dynamically-typed value from its term representation. By combining _dynamic construct, you can convert Dynamic.term structures to statically-typed ML values.

The following interactive session is an example of constructing an ML record of different type from another ML record.

# open Dynamic;
...
# val x = {name = "Sendai", wind = 7.6};
val x = {name = "Sendai", wind = 7.6} : {name: string, wind: real}
# val d = dynamicToTerm (dynamic x);
val d = RECORD {#name => STRING "Sendai", #wind => REAL64 7.6} : term
# case d of
>   RECORD m =>
>   RECORD (RecordLabel.Map.insert
>             (m, RecordLabel.fromString "weather", STRING "cloudy"))
>   | x => x;
val it =
  RECORD
  {#name => STRING "Sendai", #weather => STRING "cloudy", #wind => REAL64 7.6}
  : term
# termToDynamic it;
val it = _ : void dyn;
# _dynamic it as {name:string, wind:real, weather:string};
val it =
  {name = "Sendai", weather = "cloudy", wind = 7.6}
  : {name: string, weather: string, wind: real}