newsfilter.io
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 Foo is a subtype of FooBar if every valid value of Foo is also a valid value of FooBar.
    • The coercion syntax x :> T explicitly casts expression x to type T, triggering a compiler check to verify that all values of x's original type are legal in T.
    • 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 Foo containing a recursive structure of Foo to be a subtype of FooBar containing a recursive structure of FooBar, provided the inner types satisfy the subtyping relation.
  • 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.
  • Interaction with Private Abbreviations

    • private type 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 T to int is permitted to extract the underlying value.
      • Coercion from int to T is rejected, preventing the creation of T instances that violate defined invariants.
    • 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.