Program

sealed class Program<out A>(source)

A pure, reusable description of a computation producing A. Build one with program or perform/flatMap, then apply handlers (handle, intercept, handleS, interpret) and extract the value with runOrThrow or run.

A program performs effects; it does not execute them. Each handler applied to it answers one effect family and returns a new program, still a description, with those effects gone. Nothing runs until run, runOrThrow or an edge runner such as io() forces the result, and forcing changes nothing, so one value can be interpreted any number of times, under different handler stacks.

When to use it

Take a refund flow: load the order, call the payment provider, write a ledger entry, notify the customer. As a program it is one value, and the caller decides how it runs. Production applies the real handlers. A test applies an in-memory store and a scripted provider that fails on the second call, then asserts on the exact sequence of effects performed, with no mocking framework and no interfaces to maintain. A dry run swaps in a handler that returns a planned provider reference without calling anyone and collects the ledger write instead of executing it, so the entry that would have been written comes back as data. An audit is an intercept applied in production only, logging every provider call before proceeding, which the refund code never learns about. Rollback policy is a call-site choice: handle failures outside the ledger handler and a failed notification rolls the write back, handle them inside and the write survives.

A suspend function with injected dependencies gives the first two. The rest need flags and wrappers threaded through every call, or cannot be expressed at all, because a suspend function's effects happen as it runs and cannot be reordered or withheld afterwards. A program is pure overhead for tight loops over millions of trivial effects, or for code that only needs sequencing; its place is a flow with a handful of effects per run that must be tested, previewed, audited or replayed.

Handlers

A handler dispatches on the erased class of the effect: handle<Fetch<String>, A> also matches a Fetch<Int>, and the mismatch surfaces as a ClassCastException where the value is used, so handle the star-projected family (Fetch<*>). Responses are not checked against the effect's declared response type either: nothing ties a rule's return value to it, and a wrong response fails at the value's use site. The one response the handlers reject at once is a Program returned from handle, intercept or handleS, usually a sub-program missing its .bind(); interpret is the form for a rule that means to return a program. Watch for rules whose last expression is not the intended response, such as a collection mutator returning Boolean for a Unit effect.

Handlers are applied inside out: the handler applied first sees an effect first, and an effect that a handler performs itself (a logging intercept, a fallback of recover) is seen only by the handlers applied after it. Where handlers interact, their order decides the semantics; the KDoc of attempt and transactional gives the cases.

Exceptions

Exceptions are not part of the model. An exception thrown while a program is evaluated, by a handler rule, an IO thunk, a program block or a flatMap function, propagates straight out of the interpretation: a try around a .bind() inside a block cannot catch it, finally blocks in the abandoned program do not run, and run does not catch it either, since its Result captures only an unhandled effect. Recoverable failures are effects: raise, attempt and recover.

Thread safety

A Program is immutable, and so is everything the library puts inside one: the continuations, the binds queued on them, the handlers applied so far and the captured bodies of program { } blocks. Building, combining and interpreting a program writes nothing to it and caches nothing in it, so one Program value, handled or not, may be shared between threads and interpreted by any number of them at the same time. It needs no synchronization of its own; publish it as you would any immutable object.

Everything an interpretation needs it creates for itself when a terminal operation (run, runOrThrow, io()) forces the program: the coroutines behind the blocks and rule blocks it runs, one loop per applied handler with its continuation bookkeeping, and the state of every handleS and interpretS, started afresh from the initial value. All of it belongs to that one interpretation and is discarded when it finishes; none of it is visible to another interpretation, so two threads interpreting one value get what they would get from two copies of it. An interpretation driven by io() may move between threads at every thunk, as its dispatcher decides, and stays confined all the same, since the dispatcher orders each hand-off.

What is not confined is the code a program carries. Handler rules, flatMap functions, block bodies and IO thunks run on the interpreting thread, once per interpretation, and whatever they capture is shared by every interpretation of that program. A rule that mutates a captured counter, collection or map, or that mutates the initial state of a handleS in place instead of returning a new one, makes the program share mutable state, which then needs the synchronization any shared mutable state needs. State threaded by value through handleS or interpretS is confined.

A continuation that outlives its interpretation, such as the resume of a yielded generator or a resume an interpret rule keeps for later, continues that interpretation on whichever thread invokes it, and is handed between threads like any other object. It is immutable data too: a multi-shot continuation may be resumed from several threads at once. The single-shot continuation of a block may not: its check catches a second resumption in sequence, not a concurrent one.

Inheritors

Types

Link copied to clipboard
class Done<out A>(val value: A) : Program<A>

A finished program holding its final value; it performs no effects.

Functions

Link copied to clipboard

Handle Failure as a Result: success with the final value, or failure carrying the Failure.Raise reason, in which case the rest of the program is abandoned.

Link copied to clipboard

Run every branch to completion and collect all results in order.

Link copied to clipboard
fun <A, B> Program<A>.flatMap(f: (A) -> Program<B>): Program<B>

Sequence f after this program. Evaluation timing follows the receiver: on a Program.Done value, f runs immediately at construction; on a suspended or deferred program it is queued and runs during interpretation.

Link copied to clipboard

Run this program as a generator: every Emit.Yield pauses it as a Generator.Yielded holding the rest of the program, and completion gives Generator.Finished. The yielded type is erased, so one generator() should see one yielded type T.

Link copied to clipboard
inline fun <E : Effect<*>, A> Program<A>.handle(noinline rule: suspend ProgramScope.(E) -> Any?): Program<A>

Interpret with auto-resume: the block's return value is the effect's response. For an effect that returns Unit, do the work; for one that returns a value, return it. The block may bind other programs, which run in place of the effect as in a program block, so a rule that translates its effect into I/O binds a performIO { }. The block is a one-shot coroutine: under a multi-shot handler such as collectAll, a block that binds the choice fails when resumed a second time, while one that returns without suspending is fine.

Link copied to clipboard
inline fun <E : Effect<*>, S, A> Program<A>.handleS(initialState: S, noinline rule: suspend ProgramScope.(S, E) -> Pair<S, Any?>): Program<A>

Stateful handle: the block receives the current state and returns newState to response. Mind the pair order when the state and the response share a type — response to newState is equally well-typed and silently swaps the two. The state is threaded by value, so each interpretation starts from initialState and shares nothing with another; a rule that mutates the initial state in place instead of returning a new one shares it between every interpretation of the program.

Link copied to clipboard
inline fun <E : Effect<*>, A> Program<A>.intercept(noinline rule: suspend ProgramScope.(effect: E, proceed: suspend ProgramScope.() -> Any?) -> Any?): Program<A>

Middleware: observe an effect without consuming it. proceed() re-emits the effect to the handler downstream and returns its response, so the rule decides where the effect executes and may inspect, rewrite or replace the result; a rule that answers without calling proceed() consumes the effect. Effects the rule performs itself are seen only by the handlers applied after this one, so a middleware that logs needs the log handler downstream of it.

Link copied to clipboard
inline fun <E : Effect<*>, A> Program<A>.interpret(noinline rule: (E, (Any?) -> Program<A>) -> Program<A>): Program<A>

Handle and remove every effect of family E. rule receives the effect and a resume continuation: resume(response) is the rest of the program with response as the effect's result, as a program that nothing has run yet. Return it to continue, transform it with flatMap or map or bind it in a program { } block to work on the rest's result, call it more than once to resume the same continuation more than once, or leave it uncalled to cut the program short. Every form runs on a constant stack. Applied lazily, when the program is run.

inline fun <E : Effect<*>, A, B> Program<A>.interpret(noinline transformDone: (A) -> Program<B>, noinline rule: (E, (Any?) -> Program<B>) -> Program<B>): Program<B>

Handle and remove every effect of family E, mapping the final value with transformDone. rule receives the effect and a resume continuation: resume(response) is the rest of the program with response as the effect's result, as a program that nothing has run yet. Return it to continue, transform it with flatMap or map or bind it in a program { } block to work on the rest's result, call it more than once to resume the same continuation more than once, or leave it uncalled to cut the program short. Every form runs on a constant stack. Applied lazily, when the program is run.

Link copied to clipboard
inline fun <E : Effect<*>, S, A> Program<A>.interpretS(initialState: S, noinline rule: (S, E, (S, Any?) -> Program<A>) -> Program<A>): Program<A>

Handle and remove every effect of family E, threading state S from initialState; resume takes the next state and the response, and is the rest of the program as in interpret, with the same forms and the same lazy application.

inline fun <E : Effect<*>, S, A, B> Program<A>.interpretS(initialState: S, noinline transformDone: (S, A) -> Program<B>, noinline rule: (S, E, (S, Any?) -> Program<B>) -> Program<B>): Program<B>

Handle and remove every effect of family E, threading state S from initialState through every step; transformDone sees the final state and value. resume takes the next state and the response, and is the rest of the program as in interpret, with the same forms and the same lazy application.

Link copied to clipboard
suspend fun <A> Program<A>.io(): A

Terminal suspend runner, available on every target: runs every IO thunk and returns the program's final value. Call it from a coroutine, after all other handlers, so that only IO effects remain; any other effect left fails naming itself. Thunk resumptions re-enter through the calling context's ContinuationInterceptor, so under a coroutine dispatcher interpretation stays on that dispatcher; in an interceptor-free context (a plain suspend main) the first thunk that resumes on another thread moves the rest of interpretation there, which is what ioBlocking() avoids on the JVM.

Link copied to clipboard
fun <A> Program<A>.ioBlocking(): A

JVM-only blocking edge runner for interceptor-free contexts (a plain main, a thread you own): runs every IO thunk and returns the final value, blocking the caller while a thunk is suspended. Every interpretation step stays on the calling thread; a thunk may hop threads internally, but its result is handed back before interpretation continues, so handler state needs no synchronization. Apply it after all other handlers, so that only IO effects remain; any other effect left fails naming itself.

Link copied to clipboard
fun <E, A> Program<A>.local(transform: (E) -> E): Program<A>

Run this sub-program with the environment transformed; the override ends with it.

Link copied to clipboard
fun <A, B> Program<A>.map(f: (A) -> B): Program<B>

Transform this program's final value with f. Like flatMap, f runs immediately on a Program.Done value and during interpretation otherwise.

Link copied to clipboard

Split the search: null if it has no answers, otherwise the first answer paired with the rest of the search as a replayable program. The rest is built in O(1): the first answer's own rest, then one choice over the options not yet tried — each of those is resumed only if the rest is run and reaches it. Splitting a rest again nests one more msplit interpreter around the search, so enumerating by repeated splits costs stack and time proportional to the number of prior splits — a bound set by handler nesting, not by the number of options.

Link copied to clipboard
fun <A> Program<A>.recover(fallback: (String) -> Program<A>): Program<A>

Recover from a failure: on Failure.Raise, the rest of the failed program is abandoned (there is nothing to resume into) and fallback replaces it. A failure raised inside fallback is not caught here — it propagates to the next outer recover or attempt.

Link copied to clipboard
fun <A> Program<A>.run(): Result<A>

Run a fully handled program, capturing the outcome as a Result: the final value on success, or an IllegalStateException naming the unhandled effect on failure.

Link copied to clipboard
fun <A> Program<A>.runOrThrow(): A

Extract the final value of a fully handled program, or throw naming the unhandled effect.

Link copied to clipboard
fun <E, A> Program<A>.runReader(env: E): Program<A>

Answer every Reader.Ask with env. A handler stack carries one environment type: this handler consumes every Ask above it, whatever type it was meant for.

Link copied to clipboard
fun <S, A> Program<A>.runState(initial: S): Program<A>

Handle every State operation with a state seeded from initial.

Link copied to clipboard
fun <S, A> Program<A>.runStateWithFinal(initial: S): Program<Pair<A, S>>

Like runState, but also returns the final state alongside the result.

Link copied to clipboard

Run this program as a transaction: its State effects hit a local copy of the state, seeded by reading the downstream handler, and the final local state is committed downstream only if the program completes. If it fails part-way (e.g. a Failure.Raise handled outside), the commit is part of the abandoned continuation and never runs — the downstream state stays untouched. Built from flatMap alone, so it is safe under a multi-shot handler such as collectAll: each branch reads, runs and commits independently.