Skip to content

Effects, Interpreters and Wiring

Once a domain is described as algebras (Functional Domain Modeling), something has to supply an interpreter for each algebra and decide where effects happen. There are several ways to do it, and they differ in what the types say: whether a function’s dependencies appear in its signature, whether its errors do, and whether the effects it may perform are tracked at all. Tagless final, the most discussed of them, has a note of its own: Tagless Final.

Ways to wire an algebra

ApproachHow a program gets its dependenciesWhat the type says about effects
Plain interfaces over IOconstructor or function parametersonly that some effect happens (IO[A])
Reader / Kleislian environment the computation reads (Kleisli[F, Env, A])the dependencies, in Env
Service handlea record of functions passed as a valuethe dependencies, as a parameter
Tagless finalan algebra Accounts[F] plus constraints on Fthe capabilities used, via F[_]: Monad and the algebras
Free monadsnone until interpretation: the program is datathe operations available, in the instruction set
ZIOconstructor injection wired by ZLayer; R for local contextenvironment R, typed error E, result A
Algebraic effectshandlers installed around the computationthe operations a computation may perform, in its effect type

Granin (PDF, section 13.2) compares five of these in Haskell (service handle, ReaderT, free monads, GADTs, final tagless/mtl) on simplicity, boilerplate, convenience and the language features they need (table 13.1). He finds the service handle and GADT approaches the simplest and most convenient, final tagless needs the most advanced features (type classes, phantom types, wrapped monads), and ReaderT has the most boilerplate. On testability (table 15.1) he ranks free monads best, because the program can be interpreted by a test interpreter that restricts and inspects every effect, and value- or type-based approaches over IO low, because a function can still bypass the interface and do I/O directly.

Parsons (PDF, sections 5.4-5.5 and 6.1-6.2) reaches a different pragmatic split for production Haskell: keep one ReaderT AppEnvironment IO backbone instead of stacking monad transformers (“embed, don’t stack”), run narrow subsystem monads into it with explicit runners (runSql :: Database a -> App a, runRedis :: Redis a -> App a) so database transactions don’t interleave non-rollbackable Redis writes, and choose between a service-handle record and an mtl type class by how implementations vary – a record of functions (LockService) closes over runtime connections and is trivial to wrap as a value (lockForTenTimesLonger), whereas a type class (MonadLock) gives one canonical instance per type without tracing where a record value came from.

The object-oriented counterpart

Most of these are functional versions of dependency injection:

  • Ports and adapters. In Percival and Gregory (PDF, chapter 2), a port is an abstract interface the domain needs (a repository) and an adapter is an implementation (a SQLAlchemy repository, a fake). That’s an algebra and an interpreter. Their tests use fakes, simple in-memory implementations, rather than mocks.
  • Manual DI with closures. Their chapter 13 (“Dependency Injection (and Bootstrapping)”) wires handlers to their dependencies with closures and functools.partial, a service handle in Python.
  • The composition root. Seemann (PDF, section 4.1) defines it as the single place in an application where modules are composed together; Martin (PDF, chapter 26) calls the same outermost plugin Main. Ghosh’s figure 5.4 is the same structure: only the end-user application depends on the implementations, and every other module depends only on algebras.

Reader and Kleisli

Ghosh (PDF, section 3.3.6 and section 5.2.1, “Anatomy of a module”) supplies a repository to account operations by making each operation a function from the repository:

type AccountOperation[A] = Kleisli[Valid, AccountRepository, A]

An AccountOperation[A] is roughly AccountRepository => Valid[A], where Valid is the error-and-async effect. Operations compose with andThen or a for-comprehension without mentioning the repository, and the application supplies one at the end, by running the composed operation with a real repository or a test one. The dependency is in the type, so a function that needs the repository can’t be called without one.

The cost is that the environment type grows with every dependency, and two operations with different environments don’t compose without adapting one of them. Haskell’s RIO style adapts a shared ReaderT env IO with Has* type classes (HasDbConnection env; Serrano Mena, PDF, section 22.2), though Parsons (section 5.3) warns that Has* polymorphism brings noisy type errors and prefers plain environment records for startup-created resources. ZIO’s environment type (below) was a language-level attempt to make environment composition ergonomic.

Free monads

A free monad turns a program into data. The algebra becomes a data type of instructions (OpenAccount, Debit, Credit), a program is a value built from those instructions with flatMap, and an interpreter turns the value into effects later. Ghosh (section 5.5, “Another pattern for modularization–free monads”) rewrites the account repository this way and concludes (section 5.5.5) that free monads subsume patterns such as dependency injection: the program needs no dependencies at all until it’s interpreted. In chapter 8 (section 8.4.2) he models commands as free monads over events, with persistence in the interpreter.

Granin builds his whole approach to domain modeling on them (chapter 6, “Domain modeling with free monads”). His case for them is separation: the scenario describes what should happen, and the interpreter, chosen at the edge, decides how. That’s also why they rank best for testability in his table 15.1: a test interpreter can observe or refuse every operation. Their costs, in his table 13.1, are some boilerplate (the instruction type and its interpreter) and awkwardness for some tasks.

The theory behind the interpreter is Plotkin and Pretnar’s (PDF): the free model of an effect’s operations is exactly this “program as data” structure, and a handler (an interpreter) is the homomorphism that the free model induces into another model. Algebraic effects, below, are the language-level form of the same idea.

Errors and dependencies in ZIO’s type

ZIO puts three things in one type, ZIO[R, E, A]: the environment the effect needs, the error it can fail with, and the value it produces. De Goes (PDF, section 1.4) gives the mental model as a function R => Either[E, A], which is Ghosh’s Kleisli-over-Either with the repository built into one type, without stacking transformers.

Two parts matter for type-driven design:

  • Typed errors versus defects (section 3.1, “Exceptions Versus Defects”). E holds the failures the domain expects, which the type forces callers to handle; defects (bugs, unexpected exceptions) are kept out of E and propagate separately. It’s Wlaschin’s split between domain errors and panics (Domain Modeling With Types) built into the effect type.
  • How dependencies are wired. ZIO’s environment was first used for all dependencies, as an alternative to tagless final. ZIO 2’s Service Pattern (sections 0.19 and 17.7-17.8) changed that: services are interfaces, implementations are classes that take their dependencies as constructor arguments, and ZLayer wires them together, which De Goes describes as borrowing from object-oriented design and aligning with onion architecture (section 17.4). Service interfaces don’t use the environment at all. R remains for context that can be eliminated locally, such as a Scope for resources or a transaction (section 17.3, “Typical Uses for the Environment”).

Algebraic effects and effect typing

Algebraic effects make “operations plus interpreters” a language feature. A computation performs operations (read, print, choose, raise) without saying how they’re implemented, and a handler installed around it gives them meaning, like an exception handler that can also resume the computation. Pretnar’s introduction (PDF) is the standard tutorial.

The type-driven part is the effect system. A computation’s type records which operations it may perform, so a function that can print is visibly different from one that can’t. Bauer and Pretnar (PDF) state the motivation: effect information helps programmers understand code, find mistakes, and safely rearrange, optimize and parallelize it, and a handler that deals with all of a computation’s operations turns it into a pure value.

Two caveats from Pretnar (section 6.4, “Algebraic theories”):

  • The original theory gave each effect equations as well as operations (nondeterministic choice is commutative, associative and idempotent), and the equations are what justify optimizations.
  • Many useful handlers (backtracking, for example) break those equations, so current work on handlers mostly drops them. It’s the same gap as in tagless final: the operations are typed, but the laws are left to the programmer.

Two Shonan seminar reports map the remaining engineering trade-offs (Lindley et al., PDF; Brachthäuser et al., PDF). First, implementing handlers via free monads is much slower than direct side effects, pushing languages with native handlers (OCaml 5, Koka, Links, Effekt, WasmFX) toward direct stack manipulation, capability-passing or selective CPS. Second, multi-shot continuations – handlers that resume a computation more than once for backtracking or probabilistic inference – clash with linear external resources such as file handles unless linearity or region scoping rules out closing a file twice. On ergonomics, Brachthäuser et al. (section 5) note why handlers often teach more naturally than monads: monads put semantics first (start from a carrier such as List, then derive operations), whereas effect handlers put syntax first (program against an operation interface, then pick a handler).

For agent systems, three recent designs apply these ideas at different points in the stack. Tan et al.’s Etas (PDF, arXiv:2607.17780) applies effect typing to model calls, tool calls, approvals and traces: a computation’s type separates deterministic code from model calls and externally visible actions, exposing what a LangGraph node hides (for example, that one step may send an email) – the type-level answer to the critique of step-by-step agent specifications in Declarative Design. Zhao et al.’s LACUNA (PDF, arXiv:2605.28617) uses lexical capabilities instead of effect rows: each model action fills a typed hole agent[T](task) with Scala 3 code that the host compiler type- and capture-checks in the hole’s live scope before any of it runs, rejecting ill-typed or capability-leaking snippets atomically. Yu et al.’s SHEPHERD (PDF, arXiv:2605.10913) uses runtime handlers and persistent traces: agent actions emit separate intent and outcome effects inside copy-on-write region scopes (fork, merge, discard) backed by a Git-like trace, so supervisor meta-agents can intercept destructive calls before they materialize, roll back reversible or compensable effects, and replay counterfactual branches from an earlier commit.

Embedded DSLs, initial and final

The two ways to embed a DSL mirror the initial and final encodings. In a deep embedding, the program is a data structure (an AST) that interpreters walk; in a shallow embedding, the program is directly its meaning, as functions. Gibbons and Wu (PDF) show that a shallow embedding is a fold over the deep one, so the two are less different than they look. They also qualify the “initial and final” names (section 2): the two embeddings are equivalent and both correspond to initial algebras. Carette et al. call their approach “final” because a term is represented by its denotation in a semantic algebra, not because it is a final coalgebra.

Carette et al. (section 1.3) state the final encoding in the same terms: a term is represented by its denotation in a semantic algebra, and the encoding is “a way to write a typed fold function over a typed term”. Each interpreter (evaluate, pretty-print, partially evaluate) is one algebra, and the same term works with all of them.

Two classic examples:

  • Hudak (PDF) argues for embedding DSLs in a host language rather than building them from scratch, so the DSL inherits the host’s types, modules and tools. His geometric-region example is shallow: type Region = Point -> Bool, so a region is the test for whether a point lies in it, and union and intersection are just || and && on the results.
  • Peyton Jones, Eber and Seward (PDF) describe financial contracts with a small set of combinators and give them a compositional denotational semantics that says what a contract is worth. The semantics also decides when two differently written contracts are the same.

Thompson (PDF, sections 19.3-19.4) works the trade-off on pictures and regular expressions: a shallow type RegExp = String -> Bool can only test membership, whereas a deep data RE also lets you enumerate matching strings, simplify ((e)*)* to (e)* (or normalize on construction with smart constructors), and compile to another target – though in a lazy host, recursive definitions (anbn = Eps :|: (a :*: (anbn :*: b))) silently extend a deep RE past regular languages. On the surface-syntax side, Parsons (PDF, chapter 14) catalogs the host-language tricks Haskell EDSLs lean on (do notation over State or Writer tree builders, BlockArguments, and overloaded number/string/list literals).

Library sources

  • Granin 2025, Functional Design and Architecture – chapter 6, “Domain modeling with free monads”; section 13.2 comparing service handle, ReaderT, free monads, GADTs and final tagless/mtl (table 13.1); table 15.1 on testability; on Ways to wire an algebra and Free monads
  • Parsons 2023, Production Haskell – sections 5.3-5.5 on AppEnvironment, the ReaderT pattern, and “Embed, don’t stack” (runSql, runRedis instead of transformer stacks whose rollback semantics clash); section 6.2 comparing service-handle records (LockService) with mtl type classes (MonadLock); sections 7.1 and 7.3 on decomposing input/output effects versus passing effectful functions as parameters; chapter 14 on Haskell EDSL syntax techniques (Writer/State tree builders with do notation, BlockArguments, overloaded literals with equality constraints); on Ways to wire an algebra, Reader and Kleisli and Embedded DSLs, initial and final
  • Ghosh 2017, Functional and Reactive Domain Modeling – sections 3.3.6 and 5.2.1 on repositories and Kleisli injection, figure 5.4, section 5.5 on free monads, section 8.4.2 on commands as free monads; on Reader and Kleisli, The object-oriented counterpart and Free monads
  • De Goes et al. 2025, Zionomicon – chapter 0 on the environment as an alternative to tagless final, section 1.4 on ZIO[R, E, A], section 3.1 on exceptions and defects, chapter 17 on the environment, onion architecture and the Service Pattern; on Errors and dependencies in ZIO’s type
  • Carette et al. 2009, Finally Tagless, Partially Evaluated: Tagless Staged Interpreters for Simpler Typed Languages – the paper that introduced the tagless final encoding of typed embedded languages; section 1.3 on final encodings as typed folds; on Embedded DSLs, initial and final
  • Percival et al. 2020, Architecture Patterns with Python – chapter 2 on ports and adapters, chapter 3 on fakes, chapter 13 on manual DI with closures and partials; on The object-oriented counterpart
  • Seemann et al. 2019, Dependency Injection: Principles, Practices, and Patterns – section 4.1, “Composition Root”; on The object-oriented counterpart
  • Martin 2018, Clean Architecture – chapter 11 on the Dependency Inversion Principle, chapter 22 on the Dependency Rule, and chapter 26, “The Main Component”, on Main as the outermost “dirty” plugin that wires concrete implementations and hands control to high-level policy; on The object-oriented counterpart
  • Pretnar 2015, An Introduction to Algebraic Effects and Handlers – operations, handlers and effect types, and section 6.4 on equational theories; on Algebraic effects and effect typing
  • Bauer et al. 2014, An Effect System for Algebraic Effects and Handlers – why effect types matter; on Algebraic effects and effect typing
  • Plotkin et al. 2013, Handling Algebraic Effects – handlers as homomorphisms from free models; on Free monads
  • Lindley et al. 2019, Programming and Reasoning with Algebraic Effects and Effect Handlers – NII Shonan Meeting Report No. 146 framing three connected open problems: restoring equational reasoning to handlers, closing the performance gap of free-monad implementations (direct stack manipulation, selective CPS, fusion), and preventing multi-shot continuations from misusing linear external resources such as files; on Algebraic effects and effect typing
  • Brachthäuser et al. 2023, Effect Handlers and General Purpose Languages – NII Shonan Meeting Report No. 203 on reasoning, continuation-capture performance, and lexical versus dynamic handler typing as OCaml ships built-in handlers (section 1), plus the panel contrasting monads as “semantics first” with effect handlers as “syntax first” (section 5); on Algebraic effects and effect typing
  • Tan et al. 2026, Etas: An Effect-Typed Language for Agent Systems (arXiv:2607.17780) – effect typing for model calls, tools, approvals and traces; on Algebraic effects and effect typing
  • Zhao et al. 2026, LACUNA: Safe Agents as Recursive Program Holes (arXiv:2605.28617) – sections 3 and 4: each agent action fills a typed hole agent[T](task) with Scala 3 code that the host compiler type- and capture-checks in the live lexical scope before execution, giving atomic pre-execution rejection and lexical capability confinement against prompt injection; on Algebraic effects and effect typing
  • Yu et al. 2026, SHEPHERD: Enabling Programmable Meta-Agents via Reversible Agentic Execution Traces (arXiv:2605.10913) – section 3: models agents as typed tasks, actions as separate intent and outcome effects tiered by reversibility (reversible, compensable, irreversible), environments as copy-on-write region-scoped handlers (fork, merge, discard), and histories as persistent Git-like traces; on Algebraic effects and effect typing
  • Hudak 1996, Building Domain-Specific Embedded Languages (doi:10.1145/242224.242477) – the case for embedding DSLs in a host language; on Embedded DSLs, initial and final
  • Peyton Jones et al. 2000, Composing Contracts: An Adventure in Financial Engineering (doi:10.1145/351240.351267) – contracts built from combinators, with a compositional valuation semantics; on Embedded DSLs, initial and final
  • Gibbons et al. 2014, Folding Domain-Specific Languages: Deep and Shallow Embeddings – section 2, “Embedding DSLs”, contrasts deep and shallow embeddings (only a compositional semantics fits a shallow one); section 4, “Folds”, shows that each compositional observer is a fold over the deep embedding, 4.1, “Multiple interpretations”, gets several interpretations by tupling (the banana-split law), 4.4, “Parametrized interpretations”, gives the shallow embedding as the Church encoding of the AST, so deep and shallow are each other’s inverses, and 4.7, “Modular interpretations”, assembles DSLs à la carte, the technique behind effect handlers; on Embedded DSLs, initial and final
  • Thompson 2023, Haskell: The Craft of Functional Programming, 3rd Edition – chapter 19, “Domain-Specific Languages”: stand-alone versus embedded DSLs (19.1), shallow versus deep embeddings on pictures and regular expressions (19.3-19.4), smart constructors that simplify or check invariants on deep ASTs, and how lazy value recursion extends a deep RE type past regular languages; on Embedded DSLs, initial and final
  • Serrano Mena 2021, Book of Monads, 2nd Edition – section 13.1.1, “Syntax and Interpretation”, on separating a monad’s algebra from its interpreters, on Ways to wire an algebra; section 13.3, “Initial Style”, and 13.3.1, “Free Monads”, on Free over a pattern functor with interpreters as natural transformations, section 13.4, “Operational Style and Freer Monads” (Cats’ and Scalaz’s Free are freer monads), and section 13.5, “Transforming and Inspecting Computations”, on rewriting a program before running it (a push followed by a pop), on Free monads; chapter 11, “A Solution: Monad Transformers”, and sections 14.2, “Initial and Operational Style”, and 14.3, “Extensible Effects”, on combining instruction sets with coproducts and on extensible effects as an alternative to transformers, a single Eff monad indexed by a type-level list of effects with handlers, on Algebraic effects and effect typing
  • Serrano Mena 2022, Haskell: Almost Standard Libraries – chapter 22, “Effects”, comparing concrete transformer stacks (and how layer order changes State versus Maybe semantics), mtl capability classes, the RIO (ReaderT env IO with Has* classes) pattern, and effect-system libraries (polysemy, fused-effects, freer-simple); on Ways to wire an algebra and Reader and Kleisli

Further reading:

  • Vargas 2023, Why on earth a ZIO IO monad for Scala? – sections 1-2 on how side effects break substitution and equational reasoning, motivating ZIO[R, E, A] as suspended descriptions composed with map, flatMap and orElse, and sections 3-4 building a recursive Dialogue ADT interpreted over zio.Console; on Errors and dependencies in ZIO’s type and Free monads
  • Pilquist et al. 2023, Functional Programming in Scala, 2nd Edition – chapter 9, “Parser combinators” (designing a combinator DSL’s algebra and laws before choosing its representation), and chapter 13, sections 13.4-13.6 (“A more nuanced I/O type”, “Non-blocking and asynchronous I/O”, “Capabilities”), which build Free[F, A] from scratch, define a Console instruction algebra with pure (Function0, ConsoleState) and effectful interpreters via ~>, compose free algebras, and contrast Free with capability traits (Console[F[_]]); on Ways to wire an algebra, Free monads and Embedded DSLs, initial and final
  • Rosien 2021, Essential Effects – section 1.3 on the Effect Pattern, section 8.1.1 on faking effects behind plain traits over IO (EmailDelivery), section 8.2 on deterministic clock ticking with TestContext, and Appendix B on abstracting IO to F[_]: Monad for effect polymorphism and error reduction; on Ways to wire an algebra
  • Bauer et al. 2012, Programming with Algebraic Effects and Handlers (arXiv:1203.1539) – introduces the Eff language with first-class effect instances, handlers, and stateful resources for default top-level I/O, working through state, transactions, backtracking and cooperative multithreading; on Algebraic effects and effect typing
  • Plotkin et al. 2009, Handlers of Algebraic Effects – the original ESOP 2009 paper generalizing Benton and Kennedy’s exception handler to arbitrary algebraic theories via the unique homomorphism from the free model, with stream redirection, timeout and rollback as handler examples; on Free monads and Algebraic effects and effect typing
  • Nielson et al. 1999, Type and Effect Systems – surveys typing judgements Γ^⊢e:τ^&φ\widehat{\Gamma} \vdash e : \widehat{\tau} \mathbin{\&} \varphi with annotated function arrows, subeffecting, effect polymorphism, Tofte-Talpin region inference with effect masking, and causal process-style effects; on Algebraic effects and effect typing
  • Urma et al. 2018, Modern Java in Action – chapter 10, “Domain-specific languages using lambdas”, comparing internal, polyglot JVM (Scala, Groovy) and external DSLs (10.1) and implementing one stock-trading order model with method chaining, nested functions, and lambda function sequencing (10.3); on Embedded DSLs, initial and final
  • Gibbons and de Moor 2003, The Fun of Programming – chapter 7, Elliott, “Functional images”, on Pan, a shallow DSEL in which Image a = Point -> a and Region = Image Bool, with a region algebra (7.7), implemented by a compiler that fuses and optimises the image code (7.1); on Embedded DSLs, initial and final