OCaml Modules vs Rust Traits vs ==Haskell Typeclasses
// status: seedling
These three features often get translated as “interfaces” when moving between languages. That translation is useful for the first five minutes and misleading after that. They all let us write code against an abstraction, but they put different things in the abstraction, choose implementations at different times, and expose different ways to make several implementations coexist.
This is the comparison I wish I had made before moving between the module-heavy part of OCaml - learning log, the trait-heavy world of Rust, and the typeclass-oriented Haskell experiments. The short version is:
| Feature | The abstraction packages | The usual choice of implementation | A useful mental model |
|---|---|---|---|
| OCaml module/signature | Types, values, submodules, and their visibility | Explicitly, by a module path, functor application, or first-class module | A typed package with a namespace and possibly hidden type identities |
| Rust trait | Behavioural requirements on a type | At compile time through generics, or at runtime through dyn Trait | A set of operations a type promises to support |
| Haskell typeclass | Operations and laws intended for a type | Through instance resolution for a typeclass constraint | An implicitly supplied dictionary of operations |
None of the rows is “the more powerful interface.” They are different answers to different pressures: module boundaries, ad-hoc polymorphism, separate compilation, runtime selection, coherence, and performance.
One problem, three shapes
Suppose I want a reusable set-like collection. It needs an element type and a comparison operation. I want to instantiate it for ascending integers and perhaps also for a reversed order. The important question is not just how to spell compare; it is whether the implementation is an argument, an instance attached to a type, or a value selected at runtime.
OCaml: a signature is a package boundary
An OCaml module type describes a module's exported components. A signature can expose an abstract t, so clients can use the operations without knowing the representation. A functor is a module-level function: it accepts a module matching a signature and returns a module.
=
=
=
= MakeSet MakeSet does not ask OCaml to discover a comparison implementation for int. The module argument is explicit. The result module also carries the relationship between IntSet.elt and IntAscending.t, subject to the signature ascribed to it.
That explicitness is especially helpful when two policies should coexist:
=
= MakeSet There is no global rule saying that int has exactly one ORDERED implementation. IntSet and DescendingSet can be built in the same program because the comparison module is an ordinary argument.
Modules are also more than records of functions. They can contain nested modules, type declarations, exceptions, and signatures that hide representation. open makes names available; include re-exports components into another structure. That distinction is one of the little details I recorded in OCaml - learning log, and it is a hint that the module system is part of the language's namespace and compilation story, not merely its object story.
For runtime selection, OCaml has first-class modules. A module can be packed as a value and unpacked later. That is useful for plugin-like registries or choosing an implementation from configuration, while functors remain the natural choice for compile-time module generation.
=
=
name ^ ": " ^ format n
let result = render formatter 42The package carries a module signature. If the signature contains abstract type components, the unpacking function often needs a locally abstract type or an explicit package constraint to relate those types to its values. It is powerful, but it is not invisible typeclass inference.
Rust: a trait describes capabilities
Rust traits are behavioural contracts. A generic function can require a trait bound, which allows the body to call the trait's methods on its type parameter. The compiler usually monomorphises generic code for concrete types; a trait object such as &dyn Trait or Box<dyn Trait> instead erases the concrete type behind a pointer and uses dynamic dispatch.
use Ordering;
Here the type parameter T is chosen by the caller, while the implementation of Ordered for T is found by the compiler. The trait bound is part of the function's contract: without Ordered, add_if_new cannot call compare.
For runtime polymorphism, the boundary changes shape:
The trait object has a dynamically sized type and is used behind a pointer. A call through it is late-bound through the object's method table. This is not the same as passing an OCaml first-class module: a Rust trait object erases a concrete value's type while preserving the trait operations; an OCaml package can carry a whole module namespace, including type components, subject to its package signature.
Traits can also express associated types, supertraits, generic methods, and constants. Those features make a trait a rich contract, but they do not turn it into a namespace. Rust modules still own names, visibility, and paths; traits own capabilities and implementations.
Haskell: a class constraint supplies operations
Haskell's typeclasses make the operation requirement appear in a type signature. An instance supplies the implementation for a type. Conceptually, a constrained function receives a dictionary containing the class methods, although the language presents that dictionary implicitly.
compareOrdered = compare
addIfNew x xs
| any ((== EQ) . compareOrdered x) xs = xs
| otherwise = x : xsThe Ordered a => part is not documentation fluff. It is the constraint that permits addIfNew to use compareOrdered. Instance resolution chooses the Ordered Int implementation when the function is used with Int.
This is wonderfully concise for operations that naturally belong to a type: numeric notation, equality, ordering, serialisation, and similar APIs. It also makes the trade-off visible when I want two comparison policies for the same underlying type. Haskell's ordinary typeclass design tends toward one coherent instance for a given class/type pair; a caller cannot simply pass IntAscending or IntDescending as two ordinary values without changing the design. Newtypes are the standard escape hatch:
newtype DescendingInt = DescendingInt Int
compareOrdered (DescendingInt a) (DescendingInt b) = compare b aThe comparison policy has now become part of the wrapper type. That is a principled design, but it is a different ergonomics from passing an OCaml module argument.
Haskell modules still exist for namespacing and exports. A module declaration does not itself make a typeclass instance; the class/instance system and the module system answer different questions.
The important differences
Where the type lives
An OCaml signature can say type t and hide its representation. The type identity is part of the module package. This makes modules good at abstract data types: clients can be prevented from constructing values except through the exported functions.
Rust traits normally constrain a type that already exists. Rust can hide concrete types behind impl Trait, private fields, or module visibility, but a trait itself is not a type constructor containing an abstract t in the OCaml sense. Associated types add type-level outputs to a trait, but they still describe an implementation of a type's behaviour.
Haskell classes constrain type variables. Abstract data types are expressed with data declarations and module exports; a class does not by itself hide a representation. This separation is why Haskell code often combines a module export list with typeclass constraints.
How many implementations can be in scope
OCaml's explicit module values make multiple implementations easy. In Rust, multiple implementations of the same trait for the same type are constrained by coherence rules; use newtypes when distinct policies need to coexist. Haskell uses newtypes for the same reason, with the additional global instance-resolution story.
This is not merely syntax. If the behaviour is a policy chosen per algorithm invocation, an explicit module or ordinary function argument is often a better fit. If it is a capability that should follow the type everywhere, a trait or class can remove repetitive plumbing.
How dispatch happens
OCaml functors and Rust generic trait bounds are compile-time composition points. Haskell's dictionary passing is also normally resolved statically, though the runtime representation is an implementation detail. OCaml first-class modules and Rust trait objects make runtime choice explicit, with different packaging and dispatch costs.
Do not infer performance from the word “static” alone. In each language the optimizer, representation, allocation, and call shape matter. The useful design distinction is whether the concrete implementation is known at the call site or deliberately hidden behind a runtime value.
What the compiler can enforce
Rust trait bounds and Haskell constraints can state that a type supports an operation. OCaml signatures can additionally hide representation and constrain relationships between module types. Conversely, a Haskell class can express type-directed overloading especially elegantly, while OCaml asks for an explicit module argument or a functor.
None of these systems automatically verifies semantic laws. A type can implement compare inconsistently, violate the intended Ord/Eq relationship, or provide a surprising Show instance. The compiler checks the shape of the contract; tests and documentation still carry the laws.
A practical decision rule
When designing a new abstraction, I now ask three questions:
- Is the thing primarily a namespace and a representation boundary? Use an OCaml module/signature, a Rust module plus private types, or a Haskell module with exports.
- Is it a capability that follows a type? A Rust trait or Haskell typeclass is a natural fit. In OCaml, a signature passed to a functor or first-class module can model the same relationship explicitly.
- Should callers choose among several policies at runtime or per call? Prefer an ordinary value/function argument, an OCaml first-class module, or a Rust trait object as appropriate. In Haskell, a record of functions or a newtype often makes the choice explicit.
The most useful habit from comparing the three is to stop asking which feature is “equivalent.” Ask instead: where should the implementation choice live, and should that choice be visible in the type? That question usually determines the right abstraction before syntax enters the discussion.
Things that tripped me up
- Treating a module as a record of functions. A record carries values; a module can carry types, submodules, visibility, and signatures. First-class modules bridge the two worlds but do not erase the distinction.
- Expecting OCaml to infer a typeclass instance.
Ord.compareorInt.compareis not selected by a hidden global instance. Pass the module, use a functor, or choose an ordinary function. - Assuming a Rust trait object is an OCaml first-class module.
dyn Traitis a dynamically dispatched value behind a pointer. It does not expose arbitrary module components or an abstract type member in the same way. - Forgetting that Haskell modules and classes are separate mechanisms. A module controls names and exports; a class controls constrained operations and instances.
- Using a global instance for a per-call policy. Ascending and descending order for the same representation are a signal to use an explicit policy value or a newtype, not to fight the instance/coherence rules.
- Assuming laws are encoded automatically.
compareOrderedhas a type; it does not have a proof that it is transitive. The same is true of most “lawful” traits and classes.
References
- OCaml manual — The module system
- OCaml manual — Module expressions and functors
- OCaml manual — First-class modules
- The Rust Programming Language — Generic types, traits, and lifetimes
- Rust Reference — Traits
- Rust Reference — Trait objects
- Haskell 2010 Language Report — Types and classes
Back to Notes · see also OCaml - learning log · Monkey language interpreter made in Rust · Home.