Manuscript Offprint
arXiv:2610.26266Polarized Scheme: duality of computation, delimited control, and continuation-passing macro Interleaving
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original. This text is shared under the same licence.
Abstract
Static type systems for Scheme have traditionally followed one of two paths: manifest type checking with multi-dispatch (Clifton and Leavens, 2005) or latent occurrence typing tailored for untyped interoperation (Tobin-Hochstadt and Felleisen, 2008). In this paper, we propose Polarized Scheme, a static foundation founded upon polarized type theory and the duality of computation. In Polarized Scheme, values are positive data producers ( ) and continuations are negative observation consumers ( ). Functions operate symmetrically under dual viewpoints: as forward value-transformers and as backward continuation-transformers. Computation exists exclusively at the interaction cut executed on a focus-and-context abstract machine separating positive data focus from negative return contexts ( ). Delimited control (shift/reset) and continuation marks are expressed directly as Return Stack frame operations parameterized by the prompt's ambient answer type without polluting producer data types. Furthermore, we formalize the hygienic macro system as an interleaved continuation-passing pipeline, where macro expansion erects its own continuation hierarchy nesting into runtime evaluation. We prove Subject Reduction, Progress with respect to prompt-delimited stacks, and Duality Bisimilarity, characterize Return Stack reclamation for dynamic closures, and report on an executable reference implementation in VeGo with a verified cut-elimination dispatcher.
1 Introduction
The design of static type systems for dynamic languages like Scheme has historically focused on accommodating untyped idioms. Clifton and Leavens [2] introduced multi-dispatch annotations, while Tobin-Hochstadt and Felleisen [12] established Typed Racket based on occurrence typing and latent predicate refinement.
However, Scheme possesses a deeper foundational characteristic: first-class control. Continuations in Scheme are first-class entities that reify evaluation contexts into values. In standard type systems, continuations are forced into the value category ((cont ) or ), obscuring the fundamental asymmetry between data that is produced and computations that consume.
Drawing from polarized linear logic [7], Call-by-Push-Value (CBPV) [8], and the classical duality of computation [3, 5], we formulate Polarized Scheme. Our system establishes a strict structural divide:
-
Positive Data Producers ( ): Discrete values, constructors (units, booleans, integers, pairs, sum injections, and suspended thunks) that construct data.
-
Negative Observation Consumers ( ): Evaluation contexts, continuations, and elimination destructors ( , projections, branching cases, function applications, thunk force) that consume data.
-
Dual Function Viewpoints: Functions act simultaneously as forward value-transformers (consuming an input value to produce an answer) and backward continuation-transformers (transforming a continuation awaiting into one awaiting ).
-
The Focus-and-Context Abstract Machine: Execution is formalized as polarized cut elimination on two distinct structures: an active producer focus P and a Return Stack R of negative consumers.
-
Interleaved Continuation-Passing Macros: Rather than an isolated pre-processing pass, macro expansion is an interleaved pipeline where macro invocations erect their own continuation hierarchy that nests into evaluation.
2.1 Type Syntax
Types are strictly partitioned into positive types and negative types :
Positive Types
Negative Types
The shift type denotes a suspended computation (thunk) reified into a positive value that yields answer upon elimination. Conversely, represents a continuation consumer expecting a positive value of type .
2.2 Term Syntax
The term language consists of producers P, consumers K, and interaction cuts c:
Producers . c
Consumers
| with-cont(f, K) | prompt(c) · K | mark(k, P) · K | shift(α). c | bind(x) · K
Cuts
In Scheme s-expression concrete syntax:
• An interaction cut is written or (cut P K).
• Forward value application is written (app arg k).
• Backward continuation transformation is written (with-continuation f k) or (<-: f k).
• A function abstraction is written (lambda ([x : In] ~k) cut).
• Thunk suspension and forcing are written (thunk cut) and (force k).
- Delimited control prompts and continuation marks are written (reset cut), (shift k cut), and (with-continuation-mark key val cut).
3 Static Semantics
The type system maintains two typing contexts: mapping value variables to positive types and mapping continuation co-variables to negative consumer types .
3.1 Typing Judgments
The typing system comprises three primary judgments:
-
: Producer synthesizes positive type .
-
: Consumer expects positive input of type .
-
: Interaction cut is well-typed and delivers observable answer .
3.2 Inference Rules
Harmonized Duality of Application. Observe the complete structural duality between T-APP and T-WITHCONT:
-
T-APP views function as a producer. It builds consumer app to apply argument and continue with .
-
T-WITHCONT treats function as a continuation transformer, constructing a consumer with-cont of type to receive and pass the result via .
Typing Delimited Control. Rules T-PROMPT and T-SHIFT parameterize delimited control directly via the ambient answer type :
-
T-PROMPT establishes an inner answer domain for cut . When terminates, its result is forwarded to outer consumer .
-
T-SHIFT captures the delimited continuation slice expecting input and returning answer . The reified continuation receives type , and the replacement cut evaluates directly in place of the prompt with answer type .
4 Dynamic Semantics: The Focus-and-Return-Stack Machine
The operational semantics is defined on a focus-and-context abstract machine with configurations:
where is the active producer focus, is the top consumer, and is the lexical environment mapping variables and co-variables . When consumers are composed sequentially, they form the Return Stack .
4.1 Transition Rules
The machine transitions by resolving the interaction cut:
[Red-Pair-Fst]
[Red-Pair-Snd]
[Red-Sum-Inl]
[Red-Sum-Inr]
[Red-Thunk-Force] where
[Red-App]
where and
[Red-WithCont]
[Red-Bind]
[Red-Halt] (Normal Form Terminal)
5 Delimited Control and Continuation Marks
Unlike classic Scheme where call/cc captures the entire unbounded continuation, Polarized Scheme models delimited control via Return Stack slicing.
5.1 Prompts and Shift
A delimited prompt prompt(c) · K pushes a prompt delimiter frame onto R before evaluating the enclosed cut c. When an inner computation invokes shift(α). c', the machine searches down the Return Stack R to the nearest prompt frame:
The slice is captured and reified as a composite function:
The Return Stack is pruned directly to , and the body cut is executed with bound to reify( ).
5.2 Continuation Marks
A mark frame mark(key, val) · K attaches dynamic metadata to the current Return Stack frame. Unwinding or capturing the stack retains all active marks, allowing efficient dynamic binding and diagnostic tracing without modifying positive data types.
6 Interleaved Continuation-Passing Macro Pipeline
A central challenge in Scheme is that macro definitions can be computed and defined dynamically to apply to subsequent expressions in the same compilation stream. In Polarized Scheme, rather than relying on an unprincipled pre-processing pass, the macro engine is structured as an interleaved continuation-passing pipeline.
6.1 Syntax and Macro Representation
Surface syntax is partitioned into core forms and syntactic abstractions:
A macro transformer M is defined via pattern-matching rewrite rules:
A macro environment maps macro keywords m to their transformers M.
6.2 Expansion Judgments and Continuation-Passing Expansion
Macro expansion is formalized as a relation translating surface form into a core interaction cut . For compound expressions, expansion proceeds in continuation-passing macro style (CPMS): when expanding sub-expressions, the expander erects an expansion continuation
that receives expanded sub-terms and synthesizes the enclosing interaction cut:
\begin{aligned}&\frac{\mathrm{M-DEFVAR}}{\mathcal{E}\vdash P\rightsquigarrow P^{\prime}}\\&\frac{\mathcal{E}\vdash(\mathrm{define}\left[x:A^{+}\right]P)\rightsquigarrow\langle P^{\prime}\mid\mathrm{bind}(x)\cdot\mathrm{halt}\rangle}{\end{aligned}M-DEFFUN
M-APP
6.3 Stream Evaluation and Phase Soundness
A Polarized Scheme program is an open stream of forms . Execution threads a compilation-and-evaluation state :
defined by three interleaved transitions:
- Syntax Definition: If , the macro table is updated immediately for subsequent forms:
- Top-Level Binding: If , the cut is type-checked against , yielding . The machine evaluates . Then:
- Expression Cut: If , is type-checked and evaluated on the abstract machine to terminal value , preserving .
Theorem 6.1 (Phase Soundness). Let be a well-formed initial state. For any stream step , the resulting environment is consistent with , and all residual cuts are closed and well-typed.
7 Metatheory
We state the core metatheoretical properties of Polarized Scheme.
Definition 7.1 (Environment Consistency). A runtime environment is consistent with typing contexts and , written , if:
-
For all , .
-
For all , .
Definition 7.2 (Well-Formed Return Stack). A Return Stack is well-formed to receive answer , written , if either:
-
.
-
, where expects and yields , and .
Lemma 7.3 (Substitution). 1. If and , then .
- If and , then .
Theorem 7.4 (Type Preservation / Subject Reduction). If , ; , and , then there exist , such that ; and .
Proof Sketch. By structural induction on the transition step . For is typed by T-CUT with type . Inversion on T-PAIR yields . Inversion on T-FST yields . Therefore by T-CUT. For , inversion on T-THUNK and T-FORCE directly reconnects the suspended cut body with consumer . For , the result follows by Lemma 7.3 on the extended calling environment .
Theorem 7.5 (Progress). If and , then either and is an irreducible canonical value, or there exists a configuration such that .
Proof Sketch. By induction on the typing derivation of . Since and are empty, neither nor can be a free variable. If . , the well-formedness of the Return Stack guarantees the existence of an enclosing prompt frame, enabling the slice capture step. If , must be thunk( ) by typing inversion, enabling [Red-Thunk-Force]. For all other consumer forms, is an eliminator matching the constructor form of by polarity duality, enabling the corresponding reduction step.
Property 7.6 (Duality Bisimilarity). For any function , value , and continuation , the forward invocation and backward invocation are strongly bisimilar, resolving in one step via [Red-WithCont].
7.1 Return Stack Reclamation and Space Bounds
A major advantage of polarized duality is the clean operational separation between data construction and control unwinding.
Definition 7.7 (Return Stack Height). The height of a Return Stack is the number of active consumer frames: , , , and .
Theorem 7.8 (Tail-Call Stack Invariance). If a cut executes a tail call , then:
where the consumer depth satisfies . In particular, iterative recursion runs in Return Stack space.
Proof. Immediate from [Red-App]: the calling consumer app(P, K) is deallocated and the body's continuation co-variable is bound directly to K, restoring the caller's Return Stack height without allocating intermediate stack frames.
Dynamic Closures and Stack Allocability. A closure is dynamically limited (downward) if its invocation lifetime is strictly bounded by the activation of its defining Return Stack frame. In Polarized Scheme, because control frames on the Return Stack are popped prior to executing body cuts, on-stack closure allocations with static links can be reclaimed immediately upon function return without traversing heap-allocated garbage.
8 Case Study: Macro-Synthesized Objects, Aspects, and Continuation Precision
To evaluate the expressiveness and linguistic adequacy of Polarized Scheme, we investigate whether high-level object-oriented programming (OOP) and aspect-oriented programming (AOP) can be synthesized purely through polarized interaction cuts and hygienic macros, without extending the core calculus . In particular, we draw inspiration from Springer and Friedman's classic construction of macro-based OOP in Scheme and the Art of Programming [11], and explore how polarized duality provides an exact semantic foundation for objects, joinpoints, aspects, and behavioral subtyping.
8.1 Friedman-Style Macro Objects as Negative Consumers
Springer and Friedman [11] construct objects as procedural closures dispatching on method name symbols via case, encapsulating state in lexical bindings, and delegating unhandled messages to parent prototypes. In Polarized Scheme, this pattern maps directly onto polarized logic:
• Object Interfaces as Negative Records: An object is fundamentally an observation consumer. Its interface is a negative product of methods:
• Encapsulation via Polarity Shift: An instantiated object is a suspended computation obj :↓ . Internal private state is closed in the lexical environment and inaccessible from the outside.
• Message Passing as Interaction Cuts: Method invocation is an interaction cut . The object consumes the method selector and argument value , returning the result directly into caller continuation .
Below is the concrete implementation of a make-circle object constructor in Polarized Scheme, verified in our reference implementation:
(define (make-circle [radius : int] k) : (thunk -> (pair int int) ( int)))
< (lambda ([msg : (pair int int)] ~mret) : int < msg | (fst (with-continuation (lambda (tag) < (cons tag 1) | (with-continuation = (case (with-continuation (lambda (u) < radius | ~mret >) HALT) (with-continuation (lambda (u) < msg | (snd (with-continuation (lambda ([f : int])) < (cons radius f) | (with-continuation * ~mret) >) HALT) ) >) HALT))) >) HALT)) >) | ~k >)
Here, msg is a pair consisting of a method tag and an argument payload: tag 1 invokes get-radius (returning 5), and tag 2 invokes scale (multiplying the encapsulated radius by scaling factor f).
8.2 Aspects as First-Class Layered Continuation Constructors
A central question in the foundations of aspect-oriented software development [1,6] is how advice interacts with modular reasoning. For data objects, object creation demands precise specification of the concrete class: one writes new Circle rather than merely new Figure, because concrete fields, layout, and invariants must be allocated at instantiation time.
On the continuation side, continuations have historically been created implicitly by the compiler at call sites: evaluating implicitly creates a return frame app( ). An aspect advising an execution joinpoint exec( ) fundamentally replaces the implicit continuation constructor with a layered continuation constructor:
Where does precision arise on the continuation side? In Polarized Scheme, the duality of computation reveals that precision on the consumer side is the exact dual of constructor precision:
-
Pointcut Matching as Co-pattern Matching: Just as new Circle specifies a concrete constructor for positive data, an aspect pointcut specifies a concrete co-constructor for continuations. It pattern-matches the continuation mark stack (inspecting joinpoint tags exec(Circle.scale) vs. exec(Figure.area)) to determine whether to construct an advising continuation layer or the base return frame.
-
The Type Precision of Proceed: In around advice, the proceed keyword represents the captured delimited continuation of the joinpoint. Its precision is statically enforced by its consumer domain:
The advice cannot supply an arbitrary figure argument to a continuation expecting the specialized representation of a circle.
- Dynamic Contextual Precision via Continuation Marks: Whereas data objects possess spatial precision (memory layout), continuations possess temporal precision (causal execution stack history). By maintaining joinpoint descriptors in Return Stack continuation marks (mark( , v)), pointcuts like cflow evaluate precise stack predicates prior to continuation construction.
8.3 The Duality of Specialization: super vs. inner and Data Envelopes
The interplay between base implementations and specialized extensions can be organized along two orthogonal axes:
-
Control vs. Data Dimension: Whether the mechanism specializes computational flow or structural layout.
-
Shift vs. Prompt Direction: Whether the derived extension wraps the base from the outside (Outside-In / Shift) or the base encloses the derived specialization within a delimited boundary (Inside-Out / Prompt).
In standard object-oriented languages (Simula, Smalltalk, Java), execution follows the Shift / Outside-In paradigm: dispatch begins at the most specialized subclass, which explicitly decides whether and when to delegate upward via super(). In AOP, AspectJ's proceed() adopts this exact outside-in direction: around advice intercepts execution and chooses whether to invoke the captured
| Direction / Polarity | Control Dimension | Data Dimension |
|---|---|---|
| Shift / Outside-In (Derived wraps Base) | proceed() / super() (Specialized method wraps base continuation) | Subclass Record Extension () (Subclass ctor wraps base constructor) |
| Prompt / Inside-Out (Base encloses Derived) | inner() (BETA Method Pattern) (Base method encloses specialized hole ) | Data Envelope / Virtual Pattern () (Base structure encloses specialized payload) |
Table 1: The Polarized Duality of Specialization across Control and Data.
base continuation. However, this asymmetry creates the well-known fragile base class problem: if a subclass or aspect omits super() or proceed(), base invariants and state updates are silently bypassed.
Conversely, the Scandinavian school of object-orientation pioneered by Ole Lehrmann Madsen in BETA [10] established the Prompt / Inside-Out paradigm. In BETA, execution begins at the outermost superclass; the superclass defines the invariant protocol and explicitly calls inner() to allow derived specializations to execute inside a delimited control hole .
Crucially, this duality extends symmetrically to the data dimension:
-
Data Shift (Subclass Extension): In standard OOP, a subclass extends a superclass by concatenating fields (). The subclass acts as the outer container that inherits and owns the base components.
-
Data Prompt (Envelopes and Virtual Patterns): The data counterpart to inner() is the Data Envelope or Virtual Pattern [10]. Here, the superclass defines an outer structural frame (managing capabilities, arena boundaries, or object headers) that encloses an existential payload hole instantiated by the derived class. In data construction, the base constructor initializes the outer envelope and calls an inverted virtual allocator hook to instantiate the interior payload within the established invariants.
8.4 Spectators, Assistants, and the Aspect Liskov Principle
Barbara Liskov and Jeannette Wing [9] formulated the Liskov Substitution Principle (LSP) for data objects: a subtype must preserve all behavioral properties provable about . In aspect-oriented programming, advice is non-oblivious and intercepts execution without caller cooperation.
We formalize the Aspect Liskov Substitution Principle by categorizing advice into Spectators and Assistants [1, 4]:
Definition 8.1 (Aspect Liskov Substitution Principle). Let joinpoint specify precondition and postcondition under delimited answer type . An advising aspect is a behaviorally sound substitute for if:
- Precondition Safety: The advice precondition is weaker than the base joinpoint:
- Proceed Invariant: Any invocation of proceed() satisfies the target joinpoint's precondition:
- Postcondition Safety: The final result delivered to caller continuation K satisfies the joinpoint contract:
- Answer-Type Containment: The advice executes within the ambient prompt boundary without unhandled control escapes:
Pure Spectators (Harmless Advice). A pure aspect is a spectator: it observes cuts (e.g., auditing, contract verification) without mutating state or diverting control. In Polarized Scheme, spectators are typed as identity continuation transformers:
They must invoke proceed exactly once with unmodified argument x and return the unmodified result y, satisfying harmless non-interference ( ) [4].
Assistants (Around Advice via Delimited Control). An assistant aspect intercepts joinpoint execution and captures the delimited continuation K awaiting the method's result. In Polarized Scheme, around advice is encoded directly using with-continuation:
(define (around-aspect [target : (thunk (-> (pair int int) (~ int)))] k)
: (thunk (-> int ( int)))
< (lambda ([factor : int] ~aret) : int
< (pair 2 factor) | (with-continuation target ~aret) >) | ~k >)
(define advised-scale < c1 | (with-continuation around-aspect HALT) >) < 4 | (with-continuation advised-scale HALT) > ; yields 20
The around aspect receives the target object, constructs an interposed layered continuation that validates or transforms the scaling factor, invokes the captured method continuation (proceed), and returns the resulting value to aret.
Bracket Semantics, Destructors, and Continuation Linearity. Just as object allocation couples constructors and destructors (RAII), around advice represents a control-level Bracket Pattern (Acquire → Proceed → Release). In Polarized Scheme, the lifecycle of an aspectual continuation layer is governed by the multiplicity of the captured continuation co-variable:
• Linear Advice (= 1 proceed): Strict RAII. The advice invokes proceed exactly once. The aspect constructor (allocating ephemeral continuation marks) and destructor (releasing resources and popping marks) execute in exact mirror order around the joinpoint.
• Affine Advice ( 1 proceed): When around advice skips proceed (e.g., serving a cached value), the joinpoint is aborted. Because the Return Stack slice is abandoned, Polarized Scheme executes Return Stack unwind handlers to finalize pending mark scopes, preventing dangling resource leaks.
• Unrestricted Advice (*, multiple proceeds): If advice resumes a continuation multiple times (e.g., speculative backtracking or retries), the Return Stack slice is duplicated. To prevent double-free hazards, the type system requires that any continuation duplicated across multiple proceed calls must not close over non-copyable linear resources.
8.5 Empirical Verification in Reference Evaluator
We verified this case study across our reference implementation pipeline in VeGo. The macro expansion phase ( ) lowers both object constructor macros (define-class) and aspect interposition wrappers (define-aspect) into pure cuts. The resulting terms pass bidirectional type checking and execute on the dual-stack machine, confirming that Polarized Scheme unifies object dispatch, delimited control, and aspectual continuation layers in a single orthogonal calculus. The complete reference evaluator, test suite, and macro pipeline are provided as ancillary files (anc/) accompanying this preprint.
9 Conclusion and Future Work
Polarized Scheme provides a disciplined foundation for Scheme by embracing the duality of computation. By separating positive data producers from negative observation consumers, functions express both value-transformer and continuation-transformer semantics symmetrically. Delimited control and continuation marks operate directly on the Return Stack parameterized by ambient answer types, and continuation-passing macros interleave cleanly with runtime execution. Future work includes expanding local bidirectional type inference to higher-rank polymorphic types and compiling polarized cuts directly to a register-allocated bytecode machine.
References
[1] Curtis Clifton and Gary T. Leavens. Spectators and assistants: Enabling modular reasoning in AspectJ. In Proceedings of the 2002 Workshop on Foundations of Aspect-Oriented Languages (FOAL), pages 15–24, 2002.
[2] Curtis Clifton and Gary T. Leavens. Adding static types to scheme. Technical Report TR-05-19, Iowa State University, Department of Computer Science, 2005.
[3] Pierre-Louis Curien and Hugo Herbelin. The duality of computation. ACM SIGPLAN Notices (ICFP), 35(9):233–243, 2000.
[4] Daniel S. Dantas and David Walker. Harmless advice. In Proceedings of the 33rd ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL), pages 383–396, 2006.
[5] Paul Downen and Zena M. Ariola. Compiling with continuations and polarized sequent calculus. Journal of Functional Programming, 30:e15, 2020.
[6] Gregor Kiczales, John Lamping, Anurag Mendhekar, Chris Maeda, Cristina Lopes, Jean-Marc Loingtier, and John Irwin. Aspect-oriented programming. In Proceedings of the 11th European Conference on Object-Oriented Programming (ECOOP), pages 220–242, 1997.
[7] Olivier Laurent. Polarized proof-nets: Proof-nets for polarized linear logic. Theoretical Computer Science, 277(1–2):79–104, 2002.
[8] Paul Blain Levy. Call-by-push-value: A subsuming paradigm. Information and Computation, 193(2):89–116, 2004.
[9] Barbara H. Liskov and Jeannette M. Wing. A behavioral notion of subtyping. ACM Transactions on Programming Languages and Systems (TOPLAS), 16(6):1811–1841, 1994.
[10] Ole Lehrmann Madsen, Birger Møller-Pedersen, and Kristen Nygaard. Object-Oriented Programming in the BETA Programming Language. Addison-Wesley, 1993.
[11] George Springer and Daniel P. Friedman. Scheme and the Art of Programming. MIT Press and McGraw-Hill, 1989.
[12] Sam Tobin-Hochstadt and Matthias Felleisen. The design and implementation of Typed Scheme. ACM SIGPLAN Notices (POPL), 43(1):395–406, 2008.