Skip to content

About

Row-polymorphic / open algebraic data types and high-performance matching generics for Haskell

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

186 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

polytropos

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 Name

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.

Motivation & Architecture

What Is a Row-Polymorphic Open ADT? (In Plain English)

For developers without a background in type theory, the terminology can seem daunting. In practice, it directly solves the rigidity of traditional data types:

  1. 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).
  2. 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.
  3. 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.
  4. The Polytropos Difference: Historically, row polymorphism in Haskell was either painfully slow to compile (quadratic $O(N^{2.8})$ typeclass search) or memory-inefficient (nested Either pointer trees). polytropos solves 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 ($O(N^{2.8})$ as measured in our benchmarks) and substantial memory overhead on large data shapes.

The Unified Representation

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, and repVals holds the product's fields in row order.
  • A sum holds the active constructor: repTag stores the constructor tag, and repVals holds 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.

Relationship to Other Work & Theoretical Precedents

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.

Classic Haskell Extensible Records & Open Variants

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 $O(1)$ literal index evidence with custom human-readable diagnostics.

(For a comprehensive comparative matrix and detailed analysis across all categories, see docs/notes/RELATED_WORK_AND_PRIOR_ART.md.)

The OCaml Heritage: Polymorphic Variants & Row Typing in GHC

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:

  1. 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 (Tnil vs. an open type variable Tvar), rather than an ad-hoc phantom flag. In polytropos, 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.

  2. Structural Subtyping via Constraint Synthesis (subtype_row): OCaml's structural subtyping does not perform expensive runtime repackaging; its subtype_row and merge_row_fields algorithms check field/constructor inclusion and emit deferred unification constraints. In polytropos, the GHC typechecker plugin (Polytropos.Plugin) performs the equivalent role: it solves SubRow (record width subtyping) and SubSum (variant widening/injection) at compile time, synthesizing literal array slices and jump-table mappings with zero runtime search overhead.

  3. 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. polytropos pairs KnownHash (compile-time 64-bit FNV-1a hash synthesis) with the core Rep unpacked Word tag to achieve $O(1)$ constructor dispatch and jump-table eliminators (eliminate, matchVariant).

  4. Advancing the Memory Physics: While OCaml maintains separate heap block encodings for variant tags and record objects, polytropos advances the state of the art by collapsing both products and sums into a single unboxed Word tag + contiguous flat SmallArray (f Any) payload layout.

Techniques from large-records, large-anon, and large-generics

To achieve $O(1)$ runtime efficiency and strictly linear ($O(N)$) compile-time scaling, polytropos builds on the pioneering techniques developed in Well-Typed's large-records, large-anon, and large-generics suites:

  1. Flat arrays over nested trees: Instead of linked lists or balanced binary trees ((:*:), (:+:)), payload slots are indexed contiguously in a SmallArray (f Any). Each field is a single pointer with zero box overhead.

  2. Erased runtime representation: Field types are erased to Any inside the array, with typed access performed via unsafeCoerce under compiler-guaranteed indices. Soundness is enforced by the type system and plugin, not runtime wrappers.

  3. GHC Typechecker Plugin (TcPlugin): Type-level searches over rows during typechecking induce severe compile-time slowdowns. The polytropos TcPlugin resolves field names (FieldIndex) and constructor names (ConstructorIndex) to compile-time literal slot indices and tags directly. It synthesizes dictionary method bodies (such as RowEq and RowShow) as literal expressions without type-level list traversals.

  4. Matching Generics Layer: Following large-generics, polytropos pairs 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.

High-Leverage Abstraction Synthesis

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

Core & Compiler Plugin

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

Ecosystem Satellites

Executable Case Studies & Benchmarks

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

Documentation & Reading Paths

Upstream Toolchain & IDE Integrations

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 branch polytropos-row-completions (mirrored across GitHub, GitCode, Disroot, Framagit, and Radicle rad: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:
    # Inside repo:
    cabal repl example-resilient
    # Standalone ghci:
    ghci -package-env . -fplugin=Polytropos.Plugin
    See docs/TUTORIAL.md and docs/NEWBIE_GUIDE.md for step-by-step guides.
  • Formal Verification & Synthesis:
  • Source Code Formatters: No formatter forks needed. Upstream formatters parse polytropos code out of the box using curated profiles in rules/formatters/ (Fourmolu, Ormolu, Brittany, Floskell).
  • Authoritative Integration Catalog: See docs/developer/UPSTREAM_REPOSITORIES_AND_INTEGRATIONS.md for full branch listings, commit hashes, and ecosystem port architecture.

Build & Test

Toolchain: GHC 9.14.1 / Cabal 3.18.

cabal build all
cabal test all

Relationship to Other Work & Theoretical Precedents

polytropos is an independent project. It synthesizes two distinct PL traditions:

  1. 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.ml row unification architecture.
  2. Well-Typed's Flat Array Representation: The runtime memory model, type-erased SmallArray (f Any) storage, and GHC TcPlugin literal synthesis build upon techniques pioneered in Well-Typed's large-records, large-anon, and large-generics suites.

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.

License

This project is dual-licensed under:

You may choose to use this work under the terms of either license. See LICENSE for details.

About

Row-polymorphic / open algebraic data types and high-performance matching generics for Haskell

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages