Lecture, Tutorial
How to Use OCaml's Coercion Operator
OCaml Subtyping and Coercion Mechanisms
Scope and Context
- The discussion focuses on standard OCaml's subtyping relation, a feature distinct from Jane Street-specific implementations, though it underpins features like immutable arrays.
- The coercion operator allows explicit type conversion checks without requiring runtime re-allocation or data walking.
Polymorphic Variant Subtyping
- Subtyping is defined by value inclusion: type
Foois a subtype ofFooBarif every valid value ofFoois also a valid value ofFooBar. - The coercion syntax
x :> Texplicitly casts expressionxto typeT, triggering a compiler check to verify that all values ofx's original type are legal inT. - Incompatibility Example: A variant constructor carrying data (e.g.,
Foo of int) cannot be a subtype of a constructor without data, even if the constructor name is identical, because the set of values differs. - Recursive Subtyping: The relation applies recursively, allowing a type
Foocontaining a recursive structure ofFooto be a subtype ofFooBarcontaining a recursive structure ofFooBar, provided the inner types satisfy the subtyping relation.
- Subtyping is defined by value inclusion: type
Runtime Efficiency and Performance
- Coercions involving lists (e.g.,
[Foo]to[FooBar]) are guaranteed to be free at runtime; they perform only type checking. - Unlike explicit conversion functions that require memory reallocation and iteration, coercion operators introduce no performance overhead.
- Coercions involving lists (e.g.,
Interaction with Private Abbreviations
privatetype abbreviations allow a new type (e.g.,T) to share the representation of a base type (e.g.,int) while enforcing invariants and type distinction at compile time.- One-Way Conversion:
- Coercion from
Ttointis permitted to extract the underlying value. - Coercion from
inttoTis rejected, preventing the creation ofTinstances that violate defined invariants.
- Coercion from
- This mechanism enables efficient operations on lists of private types (converting
[T]to[int]without runtime cost) while maintaining abstraction boundaries.
Limitations and Future Topics
- The coercion operator also applies to object types, though the complexity is noted as outside the current scope.
- Upcoming Discussion: The next session will examine how coercion interacts with variant annotations during data type definitions.