Skip to content

Compositional Effects

An algebraic effect is an operation a computation requests from its context, such as drawing a random value, reading state, or adding a score, and a handler decides how each request is answered and how the computation resumes (Plotkin and Power, 2003; Plotkin and Pretnar, 2009; Bauer and Pretnar, 2015). The same random request can draw a fresh value during simulation or replay a given value during scoring, as in Pyro's effect handlers (Pyro Developers, n.d.-d).

Linguistic meanings can carry similar extra structure: several alternatives, a discourse update, or a scope-taking operation. Effect-driven interpretation composes such meanings with the functor, applicative, and monad interfaces of functional programming (Bumford and Charlow, forthcoming). quivers provides these interfaces as Python abstract classes, a function that lifts grammar rules through them, and a free-monad construction for effects given by a signature. QVR programs declare effects and handlers in the Quivers Indexed Effect Core (QIEC). Denotational Semantics gives the denotations.

Typeclass hierarchy

A type class is an interface of operations, with laws, that a type implements (Wadler and Blott, 1989). Of the classes here, fmap applies an ordinary function inside an effect, pure brings a plain value into it, apply combines effectful arguments, and bind lets the next step depend on a value produced by the previous one (McBride and Paterson, 2008). Lifting a grammar rule means extending it to arguments that carry an effect. If an adjective has two possible meanings and a noun three, lifting their combination through the alternatives effect considers the six pairs, applies the base rule to each, and collects the results.

quivers.monadic.typeclasses and quivers.arrows.typeclasses define the classes as Python abstract base classes. An effect is an instance of the classes whose operations it implements, and the lifting function below chooses lifts by those classes, never by the effect's identity. The monad classes:

Class Adds Linguistic use
Functor fmap lifting a function through an effect
Applicative pure, apply lifting a rule through an effect, argument by argument
Monad join (and the derived bind) letting an effectful argument take scope over its context
Alternative empty, alt sets of alternatives
MonadPlus both Monad and Alternative alternatives with scope-taking
Foldable / Traversable foldr, traverse running an applicative action across a structure
MonadTrans lift stacking one monad on another

The arrow classes follow Hughes (Hughes, 2000). An arrow generalizes a function. Its first runs an arrow on one component of a pair, which gives a premonoidal (Freyd) structure rather than a symmetric monoidal one (Jacobs et al., 2009).

Class Adds Use
Category_ id_arr, compose identity and composition
Arrow arr, first lifting functions and acting on one component of a pair
ArrowChoice left_arr acting on one case of a disjoint union
ArrowApply app applying an arrow given as input
ArrowLoop loop_arr feedback, for recursive definitions
ArrowZero / ArrowPlus zero_arr, alt_arr failure and choice between arrows

Function and Stochastic do not implement ArrowLoop: diagonal contraction can return several fixed points, no fixed point, or weights whose rows do not sum to one. VRel exposes this contraction for weighted relations; the trace laws require an appropriate algebra, such as a commutative semiring.

Stdlib effect instances

quivers.monadic.instances provides seven effects, each a dx.Model that holds its parameters (Continuation(answer=S) holds its answer type) and registers with its classes through ABC.register. The linguistic uses follow Bumford and Charlow (Bumford and Charlow, forthcoming).

Effect Registered as Linguistic use
Identity Monad no effect
Maybe MonadPlus presupposition failure
Alternative_ MonadPlus, Foldable, Traversable alternatives, focus, questions
Continuation(answer) Monad scope-taking, generalized quantifiers
State(state) Monad dynamic anaphora, discourse referents
Reader(env) Monad assignment functions, indexicals
Writer(monoid) Monad appositives, nonrestrictive relative clauses

Alternative_ is the powerset monad, presented by its Kleisli category \(\mathbf{Rel}\), so its morphisms are over BOOLEAN. State, Reader, Writer, and Continuation are monads on finite sets and functions: their operations act on morphisms whose rows have exactly one nonzero entry and raise ValueError on any other morphism. Writer checks at construction that its monoid is associative with a two-sided unit.

Every Monad is also an Applicative and a Functor, since the classes are subclasses of one another.

Lifting rule schemas by type class

class_directed_lifts(base_schema, effect) in quivers.stochastic.effect_lifts checks which classes an effect is an instance of and returns one lifted rule schema per applicable operation. For a base rule named r and an effect T, the lifts are:

Effect class Lifted schema Shape
Applicative pure_T_r \(X \vdash T(X)\)
Applicative apply_T_r \(T(X/Y),\ T(Y) \vdash T(X)\)
Monad bind_T_r \(T(X),\ T(Y)/X \vdash T(Y)\)
Alternative alt_T_r \(T(X),\ T(X) \vdash T(X)\)

Each lift is a SchemaDecl, the same value a QVR schema declaration produces, so a chart parser treats lifted and written schemas alike. The base rule contributes the name suffix; the displayed schema shapes are fixed. A bare Functor and arrow-only instances produce no lifts, and this operation does not run QIEC handlers.

from quivers.dsl.ast_nodes import (
    SchemaDecl,
    SchemaParameter,
    TypeName,
    ObjectProduct,
    ObjectSlash,
)
from quivers.monadic.instances import Continuation, Alternative_
from quivers.stochastic.effect_lifts import class_directed_lifts
from quivers.core.objects import FinSet

S = FinSet(name="S", cardinality=2)

forward_app = SchemaDecl(
    name="forward_app",
    parameters=(
        SchemaParameter(names=("X", "Y"), type_expr=TypeName(name="Cat")),
    ),
    domain=ObjectProduct(components=(
        ObjectSlash(result=TypeName(name="X"), argument=TypeName(name="Y"), direction="/"),
        TypeName(name="Y"),
    )),
    codomain=TypeName(name="X"),
)

cont_lifts = class_directed_lifts(forward_app, Continuation(answer=S))
# pure_Continuation_forward_app, apply_Continuation_forward_app,
# bind_Continuation_forward_app

alt_lifts = class_directed_lifts(forward_app, Alternative_())
# the same three for Alternative, plus alt_Alternative_forward_app

lift_rule_set(base_schemas, effects) returns the base schemas followed by every lift of each one under each effect. swap_rule_set(laws) returns, for each distributive law \(\lambda : S \circ T \Rightarrow T \circ S\), a schema \(S(T(X)) \vdash T(S(X))\) that exchanges the order of two effects. Both results are tuples of schemas that a chart parser takes as ordinary rules. The parser does not add them by itself, and no step of the parser applies a handler.

Algebraic effects + handlers

A signature lists the operations a computation may request without fixing how they run. The free monad over a signature represents a computation as a tree of requests waiting for answers, and a handler interprets that tree in some target monad (Swierstra, 2008; Plotkin and Pretnar, 2009). For a Choose request, one handler might pick an alternative and another might explore all of them, while the operation's type stays the same. quivers.monadic.algebraic provides:

  • Operation(name, parameter, result): one operation;
  • EffectSignature(name, operations): a signature, whose to_theory() returns it as a panproto theory with one operation per operation of the signature and no equations;
  • FreeMonad(signature): the free monad over the signature, an instance of Monad;
  • Handler(signature, target, return_clause, operation_clauses): an interpretation of FreeMonad computations in the monad target. Its clause_theory() has one operation for the return clause and one for each operation clause, and its as_theory_morphism() is the theory morphism from the signature's theory into it, sending each operation to its clause, as panproto checks it.

QIEC effect interfaces and rows

The Quivers Indexed Effect Core (QIEC) is the typed core language to which every executable QVR declaration elaborates (language reference). Each computation in it has an effect row, the list of effect instances it may still request. !{random, score} permits random draws and scoring through those two instances, and !{} permits no unhandled request. A probabilistic program's sample and observe steps request operations of the built-in random and score instances, and its [effects=[...]] option summarizes that row.

An effect declaration names an interface and its operations, and an instance declaration creates a named occurrence of it (Bauer and Pretnar, 2015). Two instances of State[Int] are thus different row entries, like two different memory cells, and handling one leaves the other. A handler matches one instance. A total handler answers every operation of its instance and removes the instance from the row, and a partial handler leaves it there for an enclosing handler. Each handler clause also declares a resumption grade, how many times it may resume the computation. Effects and handlers specifies the source forms, and Transpiler support lists which targets accept which effects.

Effects as module boundaries

A part of a model that varies between experiments, such as the world model that decides which facts hold or the readout that turns a truth value into a response, can be an effect interface rather than a value that generic code branches on. The generic module declares the interface and an instance, and performs on the instance; each experiment module exports a handler for it; the module that runs an experiment installs that handler around the generic code (effects across modules). The generic module discourse declares the sentences, the world interface and its instance, and the truth of a sentence:

discourse.qvr
export family Sentence : Type
    constructor Fact : Int -> Sentence
    constructor Not : Sentence -> Sentence
    constructor And : Sentence * Sentence -> Sentence

export effect World
    holds : Int -> Bool

export instance world : World

export define truth(s : Sentence) : Bool !{world} =
    case s motive => Bool
        Fact(n) =>
            perform world.holds(n)
        Not(p) =>
            let b <- truth(p)
            return not b
        And(p, q) =>
            let a <- truth(p)
            let b <- truth(q)
            return a && b

An experiment module exports a world model as a handler for World, here one in which the facts numbered below three hold:

worlds/small.qvr
import discourse as D

export handler small for D.World : Bool -> Bool [coverage=total, forwards=none, implementation=authored]
    return x =>
        return x
    holds(n : Int) resumes 1 =>
        resume(n < 3)

and the module that runs the experiment installs it on the instance world:

experiment.qvr
import discourse as D
import worlds.small as W

export define judge(n : Int) : Bool !{} =
    handle D.world with W.small in
        D.truth(D.And(D.Fact(n), D.Not(D.Fact(n + 1))))

Three properties make this safe and cheap.

  • Generic code cannot handle an instance it was not given. A request that reaches it through an open row tunnels past the handlers it installs (generic code and open rows).
  • The equations the generic code relies on are declared once, as a local theory of the instance, and every handler an experiment installs is checked against them.
  • A world model that answers a lookup by computing a reply and resuming is tail-resumptive, so it is compiled by evidence passing: the compiled truth calls the lookup's code directly, captures no continuation, and is fit and exported like any first-order computation (discharged handlers).

A downstream module adds a readout by exporting one more handler for the readout interface, without editing the generic module.

Bridges between monads and arrows

quivers.monadic.bridges converts between the two kinds of interface:

  • kleisli(monad) wraps a Monad as its Kleisli arrow, an instance of Arrow and ArrowApply;
  • arrow_monad(arrow) wraps an ArrowApply as a Monad.

Only arrows with app correspond to monads in this way (Hughes, 2000), so an arrow without ArrowApply has no monad counterpart.

Worked example: scope-taking via Continuation

The gallery grammar docs/examples/source/quantifier_scope/quantifier_scope.qvr derives quantifier scope with categories of continuations (Bumford and Charlow, forthcoming). Its rules write categories in Steedman notation, with the result leftmost: Fwd(A, B) is A/B, which takes a B on its right to give A, and Bwd(A, B) is A\B, which takes a B on its left to give A (Steedman, 2000). Cont(X) is a category of continuation type.

import std.semiring

object Term : FinSet 16

deduction QScope[S = std.semiring.LogProb] : Term -> Term [start=S, depth=4, tolerance=1e-5]
    atoms S, NP, N, Fwd, Bwd, Cont, span, every, dog, barks
    rule fwd_app : span(I, K, Fwd(A, B)), span(K, J, B) |- span(I, J, A) #[learnable]
    rule bwd_app : span(I, K, B), span(K, J, Bwd(A, B)) |- span(I, J, A) #[learnable]
    rule fwd_app_cont : span(I, K, Cont(Fwd(A, B))), span(K, J, Cont(B)) |- span(I, J, Cont(A)) #[learnable]
    rule pure_cont : span(I, J, A) |- span(I, J, Cont(A)) #[learnable, bounded]
    rule scope_take : span(I, K, Cont(A)), span(K, J, Bwd(B, A)) |- span(I, J, Cont(B)) #[learnable]
    rule cont_elim : span(I, J, Cont(S)) |- span(I, J, S) #[learnable, bounded]
    lexicon
        "every" : Cont(Fwd(NP, N)) = every #[learnable]
        "dog"   : N                = dog   #[learnable]
        "barks" : Bwd(S, NP)       = barks #[learnable]

fwd_app_cont is the applicative lift of forward application, Cont(A/B), Cont(B) ⊢ Cont(A), and has the same shape as the schema apply_Continuation_r that class_directed_lifts generates. pure_cont is the unit, A ⊢ Cont(A). scope_take, Cont(A), B\A ⊢ Cont(B), lets an argument whose category is a continuation take scope over the function that consumes it, and cont_elim lowers a Cont(S) to an S. These two are written by hand: the generated bind lift has the different shape T(X), T(Y)/X ⊢ T(Y).

Cited sources

Gordon Plotkin and John Power. Algebraic Operations and Generic Effects. Applied Categorical Structures, 11:69–94, 2003. URL: https://link.springer.com/article/10.1023/A:1023064908962, doi:10.1023/A:1023064908962.

Gordon Plotkin and Matija Pretnar. Handlers of Algebraic Effects. In Programming Languages and Systems, volume 5502 of Lecture Notes in Computer Science, 80–94. Springer, 2009. URL: https://link.springer.com/chapter/10.1007/978-3-642-00590-9_7, doi:10.1007/978-3-642-00590-9_7.

Andrej Bauer and Matija Pretnar. Programming with Algebraic Effects and Handlers. Journal of Logical and Algebraic Methods in Programming, 84(1):108–123, 2015. URL: https://www.sciencedirect.com/science/article/pii/S2352220814000194, doi:10.1016/j.jlamp.2014.02.001.

Pyro Developers. Poutine: a guide to programming with effect handlers in Pyro. Pyro Tutorials, version 1.9.1, n.d.-d. URL: https://pyro.ai/examples/effect_handlers.html (visited on 2026-11-06).

Dylan Bumford and Simon Charlow. Effect-Driven Interpretation: Functors for Natural Language Composition. Elements in Semantics. Cambridge University Press, forthcoming. ISBN 9781009285377. Forthcoming; publisher lists expected 2026 publication. Author preprint: arXiv:2504.00316. URL: https://www.cambridge.org/core/elements/abs/effectdriven-interpretation/56671E539160AAA1DACF8555B82A2FE4.

Philip Wadler and Stephen Blott. How to Make Ad-Hoc Polymorphism Less Ad Hoc. In Proceedings of the 16th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL), 60–76. 1989. doi:10.1145/75277.75283.

Conor McBride and Ross Paterson. Applicative programming with effects. Journal of Functional Programming, 18(1):1–13, 2008. URL: https://www.cambridge.org/core/journals/journal-of-functional-programming/article/applicative-programming-with-effects/C80616ACD5687ABDC86D2B341E83D298, doi:10.1017/S0956796807006326.

John Hughes. Generalising Monads to Arrows. Science of Computer Programming, 37(1–3):67–111, 2000. URL: https://www.sciencedirect.com/science/article/pii/S0167642399000234, doi:10.1016/S0167-6423(99)00023-4.

Bart Jacobs, Chris Heunen, and Ichiro Hasuo. Categorical Semantics for Arrows. Journal of Functional Programming, 19(3–4):403–438, 2009. doi:10.1017/S0956796809007308.

Wouter Swierstra. Data Types à la Carte. Journal of Functional Programming, 18(4):423–436, 2008. doi:10.1017/S0956796808006758.

Mark Steedman. The Syntactic Process. MIT Press, 2000. URL: https://direct.mit.edu/books/book/4283/The-Syntactic-Process, doi:10.7551/mitpress/6591.001.0001.