On this page

Subtyping and Variance with Polymorphic Variants in OCaml

Published on August 20, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A type t1 is a subtype of a type t2 when any value of type t1 can safely be used wherever a value of type t2 is expected. OCaml's Hindley-Milner type system doesn't generally support this kind of relationship — two types are either identical or unrelated — but polymorphic variants are a deliberate exception, carrying a genuine, checked subtyping relation that ordinary variants don't have. Understanding exactly how that relation works, how it's invoked explicitly, and how it propagates through containers like lists is what makes it usable as a real design tool rather than a source of confusing type errors.

The Subtyping Rule for Polymorphic Variants​

One polymorphic variant type is a subtype of another exactly when every tag in the first also appears in the second, carrying the same argument type. Consider a narrower and a broader description of a shape:


type basic_shape = [ `Circle of float ]

type shape = [ `Circle of float | `Square of float ]

Every possible basic_shape value is also a valid shape value, since `Circle of float appears in both — nothing about shape demands anything basic_shape doesn't already provide. This is the entire rule: a type with fewer tags is a subtype of a type with the same tags plus more, as long as every shared tag carries a matching argument type.

Making the Relationship Explicit With Coercion​

Unlike the flexible open-ended inference already familiar from ordinary polymorphic variant functions, moving a genuinely fixed value from a narrower type to a broader one requires an explicit coercion, written with :>:


let c : basic_shape = `Circle 2.0

let s : shape = (c :> shape)

(c :> shape) asks the compiler to verify that basic_shape really is a subtype of shape, and if so, treats the resulting expression as having type shape from that point on. When the source type is already clear from context, it can be dropped, leaving just (c :> shape) — as already shown above — since OCaml can work out c's own type without it being stated again. This coercion is a genuinely checked operation, not a blind reinterpretation of the value's bits: attempting to coerce a type that isn't actually a subtype of the target produces a compile-time error describing exactly which tag is missing or mismatched.

Variance: How Subtyping Propagates Through Containers​

Subtyping doesn't stop at bare polymorphic variant values — it extends through type constructors like tuples and lists, following a rule that matches ordinary intuition about containers: if t1 is a subtype of t1', and t2 is a subtype of t2', then t1 * t2 is a subtype of t1' * t2', and the same holds for t1 list against t1' list.


let shapes : shape list = (([ `Circle 1.0; `Circle 2.0 ] : basic_shape list) :> shape list)

A list of basic_shape values coerces directly into a list of shape values, without needing to rebuild the list or touch a single element — the coercion just reinterprets the whole list's type at once, safely, since anything that can be done with a shape (matching against its tags) is also something every element already supports by virtue of being a basic_shape. This kind of container is called covariant: subtyping on the element type carries straight through to subtyping on the container type. It's worth noting how different this is from generic containers in some other languages — a parameterized list type in Java or a template container in C++ is typically invariant in its element type by default, meaning a list of a narrower type generally cannot be used directly where a list of a broader type is expected, even when the narrower type clearly satisfies every requirement of the broader one. OCaml's polymorphic variant lists behave the more permissive way instead, and the compiler still checks the relationship rather than simply trusting it.

Why Narrowing Isn't Allowed​

The reverse operation — treating a broader-typed value as though it were a narrower one, sometimes called narrowing or downcasting — isn't permitted in OCaml. Given a shape value, there's no coercion that recovers a basic_shape, even if the specific value happens to only ever be `Circle. This is a deliberate design choice rather than a missing feature: allowing it would mean a piece of code holding a shape could effectively probe which specific narrower type a given value actually came from, which undermines the entire point of exposing only the broader type in the first place. A function that only knows it has a shape is supposed to be able to treat every shape uniformly, without any way to recover extra information the type intentionally chose not to expose.

Variance Annotations on Custom Type Constructors​

For an ordinary, fully exposed type definition, OCaml can work out on its own whether a type constructor is covariant, contravariant, or neither, just by looking at how the type parameter is actually used inside the definition. This automatic inference stops being possible once a type is made abstract in a module signature, since the signature no longer reveals the underlying definition the compiler would otherwise inspect. In that situation, variance has to be declared explicitly, using a + for covariance or a - for contravariance directly on the type parameter:


module Box : sig

  type +'a t

  val make : 'a -> 'a t

  val get : 'a t -> 'a

end = struct

  type 'a t = 'a

  let make x = x

  let get x = x

end

The + on 'a t in the signature declares that Box.t is covariant in 'a, meaning a Box.basic_shape t can be coerced to a Box.shape t the same way a basic_shape list coerces to a shape list, even though nothing about Box.t's actual internal representation is visible from outside the module to confirm that relationship independently. Getting this annotation wrong — declaring covariance for a type that isn't actually safe to treat that way — is caught by the compiler when the module is defined, not left as a trap for whoever consumes the module later.

A related subtlety: adding a type constraint to a parameterized type can block the compiler's own variance inference on that parameter, even outside of an abstract signature, since the constraint changes how the parameter can legally be used. Restoring an explicit variance annotation on the constrained parameter fixes this, letting subtyping propagate through the constrained type constructor exactly the way it would without the constraint in place.

Practical Guidance​

Subtyping through polymorphic variants tends to work best when a hierarchy of tag sets is planned deliberately from the start — a narrower type intentionally defined as a subset of a broader one's tags — rather than retrofitted onto types that grew independently of each other. Needing many scattered, ad hoc coercions throughout a codebase is usually a sign that the type hierarchy wasn't designed with this relationship in mind; a small number of coercions, applied at clear, well-chosen boundaries, is the more maintainable outcome. Wrapping a frequently repeated coercion in a small, clearly named helper function is generally clearer than writing the same :> expression inline at every call site, since the helper's name can describe the widening being performed in plain terms.

Key Takeaways​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Advanced Type System

Next

Abstract Types & Encapsulation