./jerome{m}

~/Notes/OCaml Modules vs Rust Traits vs Haskell Typeclasses.md · note · seedling · 8 min · updated

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:

FeatureThe abstraction packagesThe usual choice of implementationA useful mental model
OCaml module/signatureTypes, values, submodules, and their visibilityExplicitly, by a module path, functor application, or first-class moduleA typed package with a namespace and possibly hidden type identities
Rust traitBehavioural requirements on a typeAt compile time through generics, or at runtime through dyn TraitA set of operations a type promises to support
Haskell typeclassOperations and laws intended for a typeThrough instance resolution for a typeclass constraintAn 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.

ocaml
module type ORDERED = sig
  type t
  val compare : t -> t -> int
end

module MakeSet (Ord : ORDERED) = struct
  type elt = Ord.t
  type t = elt list

  let empty = []

  let add x set =
    if List.exists (fun y -> Ord.compare x y = 0) set then set
    else x :: set
end

module IntAscending = struct
  type t = int
  let compare = Int.compare
end

module IntSet = MakeSet (IntAscending)

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:

ocaml
module IntDescending = struct
  type t = int
  let compare a b = Int.compare b a
end

module DescendingSet = MakeSet (IntDescending)

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.

ocaml
module type FORMATTER = sig
  val name : string
  val format : int -> string
end

module Decimal = struct
  let name = "decimal"
  let format = string_of_int
end

let formatter : (module FORMATTER) = (module Decimal : FORMATTER)

let render (module F : FORMATTER) n =
  F.name ^ ": " ^ F.format n

let result = render formatter 42

The 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.

rust
use std::cmp::Ordering;

trait Ordered {
    fn compare(&self, other: &Self) -> Ordering;
}

impl Ordered for i32 {
    fn compare(&self, other: &Self) -> Ordering {
        i32::cmp(self, other)
    }
}

fn add_if_new<T: Ordered>(value: T, values: &mut Vec<T>) {
    if !values.iter().any(|existing| {
        value.compare(existing) == Ordering::Equal
    }) {
        values.push(value);
    }
}

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:

rust
trait Formatter {
    fn format(&self, n: i32) -> String;
}

fn render(formatter: &dyn Formatter, n: i32) -> String {
    formatter.format(n)
}

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.

haskell
class Ordered a where
  compareOrdered :: a -> a -> Ordering

instance Ordered Int where
  compareOrdered = compare

addIfNew :: Ordered a => a -> [a] -> [a]
addIfNew x xs
  | any ((== EQ) . compareOrdered x) xs = xs
  | otherwise                           = x : xs

The 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:

haskell
newtype DescendingInt = DescendingInt Int

instance Ordered DescendingInt where
  compareOrdered (DescendingInt a) (DescendingInt b) = compare b a

The 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:

  1. 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.
  2. 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.
  3. 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.compare or Int.compare is 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 Trait is 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. compareOrdered has a type; it does not have a proof that it is transitive. The same is true of most “lawful” traits and classes.

References


Back to Notes · see also OCaml - learning log · Monkey language interpreter made in Rust · Home.