Algebraic Effects & DI
Lexically scoped algebraic effects with capability tunneling, static service specialization, compile-time dependency-graph wiring, and isolated with resume continuations.
Declaring effects & bidirectional rows
An effect declaration specifies a named set of operations. Operations may declare
their own effect rows (bidirectional effects), making failure contracts visible at every
perform site without hidden exceptions:
effect Users with
find(id: Int) -> User ! {Fail<UserError[NotFound]>} automatically propagates
both Users and Fail<UserError[NotFound]> into any function that
calls Users.find(id).
Lexical capability passing & tunneling
Unlike dynamically scoped effect systems that search a handler stack at runtime, Exp binds every handler lexically:
- Each concrete effect
Ein a function's inferred row lowers to an explicit capability parameter. - Polymorphic effect row variables
epass as opaque capability bundles that higher-order helpers forward without intercepting (tunneling). Accidental effect capture is impossible. - Function values capture capabilities from their lexical definition site, except latent effects declared in an expected parameter type.
- Pure functions (
! {}) receive zero capability parameters and compile to Tier 0 code with 0 bytes of effect overhead.
Three static capability classes
Every handler is classified statically at its declaration site:
| Class | Definition | May escape in closures / values? | Lowering |
|---|---|---|---|
| Service | All clauses are tail-resumptive (no with resume, no abort) | Yes — first-class value (db = Postgres(url), db.find(1)) | Tier 1: static specialization / direct calls (B3 ≤ 1.05×, 0 allocs) |
| Root control | Runtime-provided effects (Async, host root effects) | Yes (within fiber / async runtime) | Tier 4: native async/await + scope token |
| Scoped control | Uses non-tail with resume, abort (Never), or multi-shot | No — second-class (E0047 if captured in escaping closure) | Tier 3 (Fail) or Tier 5 (isolated continuations) |
Compile-time dependency wiring (handle ... with)
Handlers declare their own dependencies simply by performing other effects in their bodies or
initialization statements. When you install a set of handlers with
handle expr with H1, H2, ... end (or flattened with use handle H1, H2),
the compiler runs Kahn's topological sort at compile time to wire every service directly:
- Unsatisfied dependencies propagate cleanly into the surrounding expression's effect row.
- Dependency cycles fail compilation with
E0051. - Multiple instances of the same service coexist as ordinary values (e.g.
primary = Postgres(url1),replica = Postgres(url2)). - Zero runtime service container, tag registry, or dynamic Map lookup is emitted in JS.
type User
id: Int
name: String
end
type LookupError
NotFound(Int)
end
effect Cache
get(key: String) -> Option<User>
set(key: String, user: User) -> Unit
end
effect Database
queryUser(id: Int) -> User ! {Fail<LookupError[NotFound]>}
end
effect Logger
info(msg: String) -> Unit
end
effect Users
find(id: Int) -> User ! {Fail<LookupError[NotFound]>}
end
handler MemoryCache: Cache
store = Ref.new([:])
fn get(key) store.get().get(key) end
fn set(key, user) store.set(store.get().set(key, user)) end
end
handler CachedUsers(db: Handler<Database>): Users
fn find(id)
key = "user:{id}"
match Cache.get(key) with
Some(user) then user
None then
user = db.queryUser(id)
Cache.set(key, user)
Logger.info("cached {user.name}")
user
end
end
end
handler TestDb: Database
fn queryUser(id)
if id == 1 then { id: 1, name: "Ada" } else fail(NotFound(id)) end
end
end
handler StdoutLogger: Logger
fn info(msg) print("[log] {msg}") end
end
fn main()
db = TestDb
use handle CachedUsers(db), MemoryCache, StdoutLogger
first = handle Users.find(1) with fn Fail.raise(NotFound(_)) { id: 0, name: "none" } end end
second = handle Users.find(1) with fn Fail.raise(NotFound(_)) { id: 0, name: "none" } end end
print("1st={first.name}, 2nd={second.name} (cache hit)")
endControl handlers (with resume) & Tier 5 isolation
Handlers that need non-local control flow, backtracking, generators, or probabilistic search
capture the deep continuation via with resume, plus an optional
fn value(x) ... end return-value transformer.
Crucially, Exp enforces Tier 5 isolation: continuation machinery is emitted exclusively for functions statically reachable beneath a non-tail-resumptive handler. Pure and service-only modules pay zero CPU or bundle-size cost for its existence.
effect Choose
pick() -> Bool
end
fn pairs()
a = if Choose.pick() then 10 else 20 end
b = if Choose.pick() then 1 else 2 end
a + b
end
fn allOutcomes() -> List<Int>
handle pairs() with
fn value(x) [x] end
fn Choose.pick() with resume
resume(true) ++ resume(false)
end
end
end
fn main()
outcomes = allOutcomes()
print("outcomes = {outcomes}")
end