Row-polymorphic / open algebraic data types (ADTs) and high-performance matching generics for Haskell, bringing the open row typing discipline and polymorphic variant semantics of OCaml to modern GHC.
polytropos collapses the four quadrants of nominal vs. structural products
and sums into one generic runtime representation (Rep: an unpacked tag
plus a flat SmallArray of payload slots). Moving between nominal and
structural data becomes an erased choice at the type level rather than an
impedance mismatch at runtime.
The library takes its name from the opening verse of Homer's Odyssey (1.1):
ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν;
— Odyssey 1.1–2
("Tell me, Muse, of that man of many turns, who wandered far and wide, after he had sacked the sacred citadel of Troy...")
In Homeric Greek, πολύτροπος (polýtropos) literally means "of many turns" or "much-wandering"—describing Odysseus as adaptable, resourceful, and capable of turning to many shapes to meet every circumstance without losing his identity.
In this library, polytropos describes the data representation: a single, versatile substrate that turns into products, sums, nominal declarations, and structural rows without runtime repackaging.
For developers without a background in type theory, the terminology can seem daunting. In practice, it directly solves the rigidity of traditional data types:
- Algebraic Data Types (ADTs): The two universal building blocks of typed data—Product types (structs/records where data has field A and field B) and Sum types (enums/variants where data is constructor A or constructor B).
-
Closed vs. Open: Traditional Haskell data types are closed: declared once with a fixed set of fields or constructors. Adding a field (like an authentication token to a
User) or adding a variant branch (like a new AST error node) requires defining a brand-new type and writing tedious conversion boilerplate. Open types can be constructed, extended, and narrowed on the fly without intermediate wrapper types. -
Row Polymorphism: A "row" is an unordered collection of named fields (like database columns). Row polymorphism allows writing functions that operate on any record containing at least certain fields (or any variant handling at least certain cases), while the compiler statically tracks and preserves all the other remaining fields (
r). Unlike OOP inheritance, no fields are sliced or erased, and no runtime downcasts are needed. -
The Polytropos Difference: Historically, row polymorphism in Haskell was either painfully slow to compile (quadratic
$O(N^{2.8})$ typeclass search) or memory-inefficient (nestedEitherpointer trees).polytropossolves this by collapsing products and sums into a single flat runtime representation (a tag plus a contiguous array) and using a GHC typechecker plugin to resolve field indices into literal numbers at compile time in$\mathcal{O}(1)$ .
In mainstream Haskell, data types are divided into two orthogonal axes:
- Products vs. Sums: records and tuples vs. algebraic variants and coproducts.
- Nominal vs. Structural: closed, named declarations (
data Person = ...) vs. open, anonymous rows (Record '[ "name" := String, ... ]).
Combining these typically requires fragmented libraries: records use nominal
syntax or row libraries like large-records / vinyl, while extensible variants
rely on nested Either trees, Data.OpenUnion, or complex GADT coproducts.
Standard type-level list induction or GHC.Generics binary trees ((:*:),
(:+:)) impose quadratic or cubic compile-time scaling (
polytropos unifies products and sums under a single core representation:
data Rep (f :: Type -> Type) a = Rep
{-# UNPACK #-} !Word
!(SmallArray (f Any))- A product is a degenerate sum: its constructor tag is always statically
0, so the tag folds away, andrepValsholds the product's fields in row order. - A sum holds the active constructor:
repTagstores the constructor tag, andrepValsholds the payload slots of that selected constructor. - Four quadrants, one representation:
| Quadrant | Type level | Runtime representation |
|---|---|---|
| Deep nominal product | Closed data decl |
Tag 0 + flat array of fields |
| Deep structural product | Open row Row |
Tag 0 + flat array of fields |
| Structural sum of nominal products | SumRow of nominal types |
Tag t + 1 slot |
| Nominal sum of structural products | Closed decl of Rows |
Tag t + flat array of fields |
Because the runtime layout is identical, hybrid nominal-structural conversions are zero-cost coercions.
polytropos builds upon extensive prior art across two decades of typed functional programming research. It acknowledges earlier Haskell libraries as foundational efforts toward similar ends, while resolving the specific performance and ergonomic bottlenecks that historically limited their adoption.
Prior efforts to bring structural rows and extensible variants to Haskell explored several distinct design points:
-
vinyl: A pioneering library establishing type-level list indexing and higher-kinded data (HKD) universes. However, its reliance on recursive typeclass induction induces superlinear compile-time scaling ($O(N^{2.8})$ in Core) and deep category-theoretic abstractions (RecElemFCtx,ElField) with high cognitive overhead. -
superrecord: Introduced compile-time field offset computation by sorting symbol lists via type families, demonstrating the performance benefits of flat arrays, but putting severe pressure on GHC's constraint solver at scale. -
row-types: Formalized Daan Leijen's row calculus in Haskell with first-class row equality, though encountering stuck type families during type inference failures. -
extensible: An ambitious multi-paradigm framework unifying records, variants, and effects under custom type-level combinators, with steep syntactic complexity. -
open-adt&world-peace: Popularized lightweight open coproducts and tagged variant unions (OpenUnion), though relying on linear Peano tag traversals or disjoint record/variant representations.
polytropos recognizes these libraries as valuable predecessors striving toward the same ideal. It advances beyond them by: (1) collapsing products and sums into one uniform flat runtime representation (Rep: tag + flat array of payload slots), and (2) delegating all symbol-to-slot and subrow/subsum resolution to a native TcPlugin that emits
(For a comprehensive comparative matrix and detailed analysis across all categories, see docs/notes/RELATED_WORK_AND_PRIOR_ART.md.)
Mainstream Haskell historically lacked a native counterpart to OCaml's battle-tested
row typing system. In OCaml (grounded in the foundational type-theoretic work of Jacques
Garrigue, Didier Rémy, and Jérôme Vouillon), polymorphic variants ([> Tag of a ]and[< Tag of a ]) and object rows demonstrate that extensible data structures do
not require runtime conversion gymnastics, nested Either trees, or global constructor
registrations.
polytropos deliberately borrows and adapts OCaml's row typing discipline to Haskell:
-
Unified Open and Closed Row Algebra: In OCaml, open and closed variants share the identical internal type shape (
Tvariant { row_fields; row_more; closed; fixed }). Closedness is simply a property of the row tail (Tnilvs. an open type variableTvar), rather than an ad-hoc phantom flag. Inpolytropos, nominal data types and open structural rows inhabit the same row algebra: closed types are the closed boundary of the same algebra open rows use, ensuring seamless backward compatibility without artificial wrapper types. -
Structural Subtyping via Constraint Synthesis (
subtype_row): OCaml's structural subtyping does not perform expensive runtime repackaging; itssubtype_rowandmerge_row_fieldsalgorithms check field/constructor inclusion and emit deferred unification constraints. Inpolytropos, the GHC typechecker plugin (Polytropos.Plugin) performs the equivalent role: it solvesSubRow(record width subtyping) andSubSum(variant widening/injection) at compile time, synthesizing literal array slices and jump-table mappings with zero runtime search overhead. -
Compile-Time Tag Hashing &
$O(1)$ Dispatch: OCaml polymorphic variant tags (e.g.`Tag) are hashed integer tags computed at compile time, allowing open pattern matching and dynamic dispatch without a central registry.polytropospairsKnownHash(compile-time 64-bit FNV-1a hash synthesis) with the coreRepunpackedWordtag to achieve$O(1)$ constructor dispatch and jump-table eliminators (eliminate,matchVariant). -
Advancing the Memory Physics: While OCaml maintains separate heap block encodings for variant tags and record objects,
polytroposadvances the state of the art by collapsing both products and sums into a single unboxedWordtag + contiguous flatSmallArray (f Any)payload layout.
To achieve polytropos builds on the pioneering techniques developed in Well-Typed's
large-records, large-anon, and large-generics suites:
-
Flat arrays over nested trees: Instead of linked lists or balanced binary trees (
(:*:),(:+:)), payload slots are indexed contiguously in aSmallArray (f Any). Each field is a single pointer with zero box overhead. -
Erased runtime representation: Field types are erased to
Anyinside the array, with typed access performed viaunsafeCoerceunder compiler-guaranteed indices. Soundness is enforced by the type system and plugin, not runtime wrappers. -
GHC Typechecker Plugin (
TcPlugin): Type-level searches over rows during typechecking induce severe compile-time slowdowns. ThepolytroposTcPlugin resolves field names (FieldIndex) and constructor names (ConstructorIndex) to compile-time literal slot indices and tags directly. It synthesizes dictionary method bodies (such asRowEqandRowShow) as literal expressions without type-level list traversals. -
Matching Generics Layer: Following
large-generics,polytropospairs row-polymorphic variants with a datatype-generic programming layer that avoids intermediate generic representations, enabling boilerplate-free derivation of serialization, database mappings, and codecs at linear compile-time cost.
As explored in our design records and transcripts, polytropos is designed to
serve as an architectural foundation alongside:
- Algebraic Effect Systems (e.g.
kernmantle,effectful): decoupling the capabilities of a program (effect rows) from its data shapes (variant rows). - Profunctor Optics & Codecs: defining bidirectional readers and writers over extensible records and variants with zero synchronization boilerplate.
-
packages/polytropos-core: The core representation (Rep,RowRep), type-level vocabulary (Row,SumRow), field projection and mutation, and evidence classes (RowEq,RowShow,RowEqSum,RowShowSum,FieldIndex,ConstructorIndex). -
packages/polytropos-plugin: GHC typechecker plugin (Polytropos.Plugin) that solves row constraints and synthesizes literal evidence bodies and$O(1)$ jump tables at compile time.
-
packages/polytropos-mcp: Model Context Protocol (MCP) JSON-RPC 2.0 server with OpenAPI schema synthesis and$O(1)$ jump table dispatch. -
packages/polytropos-aeson: Fast AesonToJSON/FromJSONserialization and schemas for open rows. -
packages/polytropos-openapi3: OpenAPI 3.0 schema generation for open records and variants. -
packages/polytropos-rel8: Oliver Charles'rel8PostgreSQL schemas (PolyRow) and type-safe query expressions. -
packages/polytropos-persistent: Yesodpersistent[PersistValue]marshalling andPolyRowEntityschemas. -
packages/polytropos-hasql: High-throughput PostgreSQL binary decoding via Hasql. -
packages/polytropos-beam: Beam relational table and query integration. -
packages/polytropos-cbor: Binary CBOR serialization viaserialise. -
packages/polytropos-dhall: Dhall configuration language codecs and generic adapters (GenericFromDhall/GenericToDhall) for open records, variants, HKD, and nominal data types. -
packages/polytropos-cassava: High-throughput CSV encoding/decoding viacassava. -
packages/polytropos-generics:GHC.Genericsbidirectional mappings between nominal types and open rows. -
packages/polytropos-lens,polytropos-optics,polytropos-profunctors,polytropos-microlens: Optics, prisms, and traversals. -
packages/polytropos-quickcheck: QuickCheck arbitrary generation and co-arbitrary testing.
examples/: Interactive tutorial companion executables:example-nanopass(Nanopass compiler pass & desugaring)example-resilient(Resilient parsing & error ASTs)example-database(Rel8 queries & Persistent serialization)example-effects(Extensible algebraic arrow ropes)example-mcp-server(Federated Context & Memory MCP server capstone)
benchmark/variants: Empirical compile-time measurement harness validating linear scaling against plain GHC data types and type-level search.
Package roles, directory conventions, and reuse rules are documented in
docs/registers/PACKAGES.md.
- Hands-on Tutorial: Start with
docs/TUTORIAL.mdfor the foundational 5-lesson curriculum and real-world worked case studies (Nanopass compilers, resilient parsing, relational databases, algebraic effect ropes, and the federated Context & Memory MCP Server capstone). - Newcomer / Contributor: See
docs/NEWBIE_GUIDE.mdfor token-conservation workflows, symbol navigation, and build commands. - Maintainer / Lead: See
docs/MAINTAINER_GUIDE.mdfor engineering governance, plugin invariants, and the zero-contamination doctrine. - Architectural Overview: Read
docs/notes/POLYTROPOS_DESIGN.mdfor canonical architectural decisions (D1–D10) and open questions. - Design Review: Read
docs/notes/DESIGN_REVIEW_CLAUDE-OPUS-4.6.mdfor the comprehensive design review and ecosystem deployment synthesis. - Empirical Evidence:
benchmark/variants/README.mddemonstrates the compile-time scaling of plugin-emitted literals vs. type-level search. - Ideation & Transcripts:
docs/transcripts/gemini-powerful-abstraction-techniques-in-haskell.md: Discussion of high-leverage Haskell abstraction patterns (effects, open ADTs, generics, profunctors).docs/transcripts/gemini-large-data-hybrid-variant-records-spec.md: Early transcript exploring hybrid nominal-structural variant records.
- Theoretical Foundations & Row Algebra:
docs/notes/OCAML_BACKWARD_COMPAT_ROW_ALGEBRA.md: Deep-dive into OCaml'sctype.mlrow representation and how backward compatibility is maintained without ad-hoc flags.docs/notes/OCAML_ROW_TAIL_SUBTYPE_MECHANISM.md: Detailed analysis of OCaml'ssubtype_rowandunify_rowtail-merging algorithms.docs/notes/ROW_ROLE_JUDGEMENT_SKETCH.md&docs/notes/ROW_ROLE_DEFNS_DRAFT.ott: Formal typing judgements bridging OCaml row algebra with GHC Core role semantics.
- Developer & Tooling Integration:
docs/developer/UPSTREAM_REPOSITORIES_AND_INTEGRATIONS.md: Authoritative catalog of upstream repositories modified for polytropos (HLS autocompletions & hovers, effect system ports, toolchain forks, and why formatters need no forks).docs/developer/LIQUIDHASKELL_AND_SYNQUID_GUIDE.md: Developer guide for out-of-process LiquidHaskell formal verification contracts and Synquid type-directed program synthesis.rules/README.md: Pre-tested downstream configuration library (Fourmolu, Brittany, Floskell, Ormolu, Stan, HLint, Retrie, Tricorder).
- Corpus Map: See
docs/INDEX.mdfor full document inventory and reading paths.
To deliver a fast, frictionless development workflow, polytropos integrates with the broader Haskell developer ecosystem:
- Haskell Language Server (HLS):
Standard HLS does not recognize row-polymorphic dot access (
rec.field). We maintain an upstream HLS fork branchpolytropos-row-completions(mirrored across GitHub, GitCode, Disroot, Framagit, and Radiclerad:z2PsuDALqgWmYqoc978SgpPTVNT5o) providing:- Context-aware autocompletion for row fields and variant constructors.
- Readable hover type summaries (e.g.
Record { name :: String, age :: Int }instead of raw compiler type families). - Code actions for
REC { .. }/VAR { .. }wildcard expansion and typo QuickFixes. - To install:
git clone https://github.com/NadiaYvette/haskell-language-server.git -b polytropos-row-completions cd haskell-language-server && cabal build exe:haskell-language-server
- Interactive REPL Exploration (
cabal repl,ghci,stack repl): Launch interactive REPL sessions with compiler plugin support preloaded:See# Inside repo: cabal repl example-resilient # Standalone ghci: ghci -package-env . -fplugin=Polytropos.Plugin
docs/TUTORIAL.mdanddocs/NEWBIE_GUIDE.mdfor step-by-step guides. - Formal Verification & Synthesis:
- LiquidHaskell: Out-of-process formal verification of array bounds and memory safety (
docs/developer/LIQUIDHASKELL_AND_SYNQUID_GUIDE.md). - Synquid: Out-of-process type-directed synthesis of row eliminators and adapters.
- LiquidHaskell: Out-of-process formal verification of array bounds and memory safety (
- Source Code Formatters:
No formatter forks needed. Upstream formatters parse
polytroposcode out of the box using curated profiles inrules/formatters/(Fourmolu, Ormolu, Brittany, Floskell). - Authoritative Integration Catalog:
See
docs/developer/UPSTREAM_REPOSITORIES_AND_INTEGRATIONS.mdfor full branch listings, commit hashes, and ecosystem port architecture.
Toolchain: GHC 9.14.1 / Cabal 3.18.
cabal build all
cabal test allpolytropos is an independent project. It synthesizes two distinct PL traditions:
- OCaml's Row Typing & Polymorphic Variants: The row algebra, open/closed tail
mechanics, and structural subtyping discipline are directly informed by Jacques
Garrigue's polymorphic variants and the OCaml typechecker's
ctype.mlrow unification architecture. - Well-Typed's Flat Array Representation: The runtime memory model, type-erased
SmallArray (f Any)storage, and GHCTcPluginliteral synthesis build upon techniques pioneered in Well-Typed'slarge-records,large-anon, andlarge-genericssuites.
It shares a documentation framework with the sarutahiko project but maintains its own
naming range, roadmap, and design.
large-data (the large-records fork) is a co-development reference checkout;
no code is copied from it, and third-party derivations and licenses are tracked
in THIRD_PARTY.md and docs/notes/PROVENANCE.md.
This project is dual-licensed under:
- European Union Public Licence (EUPL) version 1.2 (
LICENSES/EUPL-1.2.txt) - Apache License, Version 2.0 (
LICENSES/Apache-2.0.txt)
You may choose to use this work under the terms of either license. See LICENSE for details.