On this page
Algebraic Effects
Halyard tracks side effects in the type system: a function's type includes which effects it may perform. You control effects by installing handlers — no monads, no async/await, no checked exception machinery required.
Declaring an effect
An effect block defines a named capability and its operations:
effect IO
readLine : String
writeLine : String -> ()
Each operation name becomes a callable in scope when the effect is in scope.
effect Rng
nextInt : Int -> Int -> Int
Effectful function types
A function that may perform the IO effect writes ->{IO} on the arrow:
fn greet : String ->{IO} ()
fn greet name = writeLine ("Hello, " ++ name)
Multiple effects are comma-separated inside the braces:
fn rollAndLog : Int ->{Rng, IO} Unit
fn rollAndLog max =
let n = nextInt 1 max
writeLine (Int.toString n)
A bare -> means no row was written — the row is INFERRED from the body. ->{} is a
written claim of purity, and the compiler CHECKS it. See
What the effect row guarantees below for exactly
what that check covers; this guide states it once, there.
Calling operations
Operations are called like ordinary functions:
fn askName : String ->{IO} String
fn askName prompt =
writeLine prompt
readLine
If readLine and writeLine are called with no IO handler installed, the VM
raises UnhandledEffect IO at RUN time, with a hint naming the effect and
operation to handle. IO is one of the ambient stdlib effects, which the compiler
allows at the top level; for the missing handlers it DOES catch, see
What the effect row guarantees.
Handling effects
handle runs a body under a handler block. Each arm matches one operation, and
the arms must cover EVERY operation of the effect:
effect IO
readLine : String
writeLine : String -> ()
let result =
handle (askName "Name?")
writeLine s -> ()
readLine -> "default"
Tail arms (op args -> body) observe the operation and provide the value it
returns. The computation continues with that value, so the arm's body becomes
the operation's result.
An arm's parameters are typed from the operation's declared signature: in
writeLine s -> () the parameter s is a String, because writeLine is
declared String -> (). Use _ for a parameter you do not need:
handle (logAll [1, 2, 3])
logItem _ -> ()
Control arms (ctl op args -> body) take the continuation themselves.
Inside a ctl arm, resume is a one-shot continuation that resumes the paused
computation with a given value:
effect Greeter
greet : String -> String
let mocked =
handle (greet "Bob")
ctl greet name -> resume "mocked-greeting"
resume value continues the computation from the point where the operation was
called. Each continuation may be used at most once.
The resumed value becomes the operation's result, so it must have the operation's declared result type, as a tail arm's body must:
-- `resume` hands its value back as the operation's result, so it must have the
-- operation's declared result type: `get` returns an `Int`.
effect Ask
get : Int
fn useIt : () ->{Ask} Int
fn useIt u = get + 1
handle (useIt ())
ctl get -> resume "one"
Compiled
An arm implements its operation at every type the operation's signature allows. For
pick : a -> a, the arm pick n -> 5 is rejected: handle (pick "s") would hand an
Int back where a String is used. pick n -> n is fine.
resume must be the LAST thing a ctl arm does. An arm that resumes and then
continues would need the VM to hand control back to the arm, which it does not
do — so code after resume is rejected (ResumeNotInTailPosition) rather than
compiled and silently skipped.
resume must also appear directly in the arm — not inside a lambda written
in that arm:
-- rejected: the `resume` is inside a closure
let r = handle (get 1)
ctl get n ->
let f : Int -> Int = |x| resume x
resume (f 5)
A closure looks like it defers the resume to whenever it is called, but the
arm's continuation is not a value the closure can carry around: the call may
happen after the arm has already returned, or never. Lambdas that do NOT resume
are fine in an arm, and are the normal way to shape a resumed value:
let r = handle (get 1)
ctl get n ->
let double : Int -> Int = |x| x * 2
resume (double 5)
Effect polymorphism
Higher-order functions like List.map are effect-polymorphic: if the callback
performs effects, the map call does too.
An operation is NOT a value, though, so you cannot hand one to List.map
directly — List.map writeLine is BareOperationReference (see
What the handler machinery checks). Wrap it
in a function:
-- List.map : (a ->{| e} b) -> [a] ->{| e} [b]
fn logIt : String ->{IO} ()
fn logIt s = writeLine s
let writeAll : List String ->{IO} List Unit
= List.map logIt
List.map never forces you to make your callback pure — the wrapper above is
about operations not being first-class values, not about effect polymorphism.
What the handler machinery checks
Handlers RUN, and the compile-time checks that the handle construct itself
needs are enforced, each with an exact error. (These are checks on operations and
handler shape; for the row on the arrow see
What the effect row guarantees.)
| program | error |
|---|---|
| a handler missing an arm for one of the effect's operations | NonExhaustiveHandler |
| an arm naming an operation the effect does not declare | UndeclaredEffectOp |
one handle whose arms name operations from two effects | MultiEffectHandle |
a top-level fn/let/export/import shadowing an operation name | BinderShadowsOperation |
| an operation sharing a name with an in-scope trait method | OperationShadowsTraitMethod |
| an operation declared twice in one effect, or two effects sharing a name | parse errors: Operation 'x' is already declared in effect 'E', Effect 'E' is already declared in this scope |
| a bare call whose name two in-scope effects declare | AmbiguousEffectOp |
| an operation applied to too few arguments | PartialOperationApplication |
| an operation of arity > 0 used as a value | BareOperationReference |
an operation used with >> or << | OperationInComposition |
resume after which more code follows in a ctl arm | ResumeNotInTailPosition |
resume outside a ctl arm | ResumeOutsideHandler |
resume inside a lambda written in an arm | ResumeNotInTailPosition / ResumeOutsideHandler |
a ctl arm that can return without resuming | CtlArmMustResume |
A ctl arm must resume on every path
A ctl arm intercepts the operation and has to hand control back. An arm
that returns without resuming discards the computation it interrupted, so it
is rejected rather than silently dropped:
handle (greet "Bob")
ctl greet name -> "oops" -- CtlArmMustResume
handle (greet "Bob")
ctl greet name -> -- fine: every path resumes
if name == "Bob" then resume "hi" else resume "hello"
"Every path" means both branches of an if and every branch of a case,
not merely the last expression.
Where a handle may appear
Both forms work: a module function may PERFORM an effect and leave it to the call site, and it may HANDLE one itself.
-- A module function may handle an effect itself, not only perform it
effect S
get : String -> String
module Store exposing fetch, cached
fn fetch : String ->{S} String
fn fetch k = get k
-- `cached` has a PURE arrow, because the `handle` below discharges `S`.
-- `fetch` keeps `->{S}` and hands the effect to its caller instead.
fn cached : String -> String
fn cached k = handle (fetch k)
get k -> "MOCK"
Store.cached "key"
Compiled
Store.cached has a pure arrow precisely because the handle inside it
discharges the effect; Store.fetch carries ->{S} and hands it on, so a
caller can handle it at the call site instead:
let r = handle (Store.fetch "key")
get k -> "MOCK"
A handle inside a module function used to be rejected
(HandleInsideModuleFunction), as an implementation restriction rather than a
language design choice. A module body is now a compilation unit of its own, so
the restriction is gone.
One limit remains, and it is about the module's INTERFACE rather than about
handle: an effect DECLARED inside a module body can be performed and handled
by that module's own members, but a caller cannot handle it. An exposing list
names functions and types, so there is no way to expose an effect, and a
top-level handle (M.go "in") reports UndeclaredEffectOp. Declare the effect
at the file's top level if callers need to handle it.
A handle handles exactly ONE effect: the PushHandler instruction carries a
single effect label. Nest handles to handle several.
An operation is not a VALUE. greet on its own performs a zero-argument
operation; for an operation that takes arguments there is no way to write its
name without calling it, and it cannot be passed to List.map or composed.
That follows from the design choice that calling an operation IS performing it.
What the effect row guarantees
The effect ROW on an arrow — the {IO} in String ->{IO} Unit — is a claim the
compiler verifies. This section is the one place this guide says what that check
covers; every other mention of it points back here.
What is checked
For a fn declaration — at the top level or inside a module — the compiler
infers the row of the body and compares it against the row you wrote:
- a
->{}function that performs an effect is anEffectRowMismatch, and so is a->{IO}function that performs something outside{IO}; - a row naming an effect no
effectblock declares is anUndeclaredEffect; - a row can be written on each arrow of a curried signature, and what the body
performs directly is compared arrow by arrow, so in
fn logTo : Path -> String ->{IO} Unitthe{IO}is what happens when theStringis applied, not when thePathis; - the INFERRED row reaches callers: a
->{}function that calls a bare-arrow helper which performs is rejected, whichever of the two is declared first, and mutually recursive functions are solved as one group; - a written, closed row on a callback SLOT is a demand on the argument's own row,
compared at each call site —
fn takes : (Int ->{} Int) ->{} Intis how you write that demand; - a direct perform at the top level, with no handler installed and no row
declaring the effect, is a compile-time
UnhandledEffectat the perform's span. The ambient stdlib effects (IO,Net,Proc,Clock,Http,IOTrace,Rng) are exempt: they are allowed at the top level and acrossrunboundaries, where the side-effect boundary lives; handle @Labelcross-checks the annotation against the operations its arms name.
A function declared pure that performs an effect is rejected:
fn badFn : Int ->{} String
fn badFn x =
readLine -- EffectRowMismatch: declared the empty row, the body performs IO.
Passing an EFFECTFUL callback where a pure row is claimed is an error:
fn effectfulCallback : Int ->{IO} Int
fn effectfulCallback x =
readLine
x
fn caller : [Int] ->{} [Int]
fn caller xs =
List.map effectfulCallback xs -- EffectRowMismatch: callback performs IO, caller declares the empty row
(The reverse is fine: a pure callback where an effectful row is expected is sound — the row variable instantiates to the empty row.)
Built-in native effects
Native stdlib functions are annotated with their effect rows. Reading a file uses
{IO}, HTTP calls use {Net}, spawning a process uses {Proc}, getting the
current time uses {Clock}. These appear in the function types you see in
documentation and hover tooltips.
IOTrace: IO you can intercept
One built-in effect is not just an annotation on a native's type. IOTrace has real
operations, and a call to one of them performs that operation rather than running
the native directly — so a handle can intercept it. The operation set is every file
and directory operation in IO, plus Http.send: 19 operations. Console IO is
deliberately not among them, and neither are the DataFrame readers and writers —
a dynamic read takes its stated schema from the call site, and an intercepted
operation is not that call site.
With no handler installed, a performed IOTrace operation runs its native and
behaves exactly as before, so nothing about existing code changes. What is new is
that you can put a handler in front of it — which is what halyard run --record
and halyard replay are built on.
The row a caller infers is {IOTrace}, not {IO}. A function that calls
IO.readFile performs an operation, and the row records the operation's effect:
fn load : String ->{IOTrace} Result String String
fn load p = IO.readFile p
Writing ->{IO} on that function is now an EffectRowMismatch: the native's own
{IO} row stays on the native's type, and does not appear in the rows of functions
that call it. A bare -> still infers the right row, which is the simplest fix for
existing code.
A catch-all arm
An effect with many operations would need one arm each. A _ arm covers every
operation the other arms do not name, and counts as full coverage:
handle @IOTrace (loadEverything ())
_ -> Ok "stubbed"
Two things come with it. A catch-all arm takes no parameters — the operations it
covers have different arities, so it reads what it was dispatched for through
Trace.currentOp () and Trace.currentArgs (). And because _ names no operation,
the handle no longer says which effect it handles: that is what the @IOTrace
annotation after handle is for. A catch-all-only handle without one is a compile
error, since there would be nothing to install.
A named arm still wins for its own operation; the catch-all takes the rest. With 19
operations, "the rest" is usually something you do not want to think about — so
Trace.passThrough () runs the operation's default interpretation, which is the stdlib
native it came from:
handle @IOTrace (loadEverything ())
readFile p -> Ok "stubbed file"
_ -> Trace.passThrough ()
That is the shape of a test double: intercept the operations you care about, leave the rest alone. In a recorded run the passed-through operation is still recorded, and in a replay it is served from the log, so the handler does not make a hole in the trace.
Summary
| Concept | Syntax |
|---|---|
| Declare effect | effect Name with op list |
| Effect row | ->{IO} on arrow, or ->{IO, Net} |
| Inferred row | bare -> (row inferred from the body) |
| Pure claim | ->{} (checked) |
| Call operation | opName args (like a function) |
| Install handler | handle body with arms |
| Tail arm | op args -> body |
| Control arm | ctl op args -> body |
| Resume continuation | resume value |
How a row is written, kept and shown
Effect rows are parsed, preserved and rendered: you can write
fn greet : String ->{IO} Unit, the formatter keeps it, and hover and the REPL
show it. What the compiler verifies about it is stated once, in
What the effect row guarantees.
The formatter CANONICALISES a row rather than preserving its exact text: labels
are reordered into name order (->{Net, IO} becomes ->{IO, Net}). A written
->{} is NOT elided — since plan 247 a bare -> and ->{} are different types
(inferred vs claimed-pure), so eliding it would change the program's meaning. No
label is ever added or dropped.
The five forms an arrow can take — and the one pair worth keeping straight,
because ->{e} and ->{| e} look alike and mean different things:
| form | meaning |
|---|---|
->{IO} | the closed row containing IO |
->{IO, Net} | a closed row with two labels |
->{| e} | an OPEN row, polymorphic in e — note the | |
-> | no row written; the row is inferred |
->{} | the closed empty row — a checked purity claim |
Labels are CAPITALISED. e is not a valid label, so ->{e} does not parse at
all -- it is a syntax error, not a row containing an effect called e.
The label parser accepts only an upper-case identifier, so the row reads zero
labels and then fails looking for the closing brace. ->{E} parses fine (a
closed row with one label E); ->{| e} parses fine (an open row with the
variable e). The PIPE is what introduces a row variable.
One rendering difference worth knowing: :doc List.map shows the DECLARED
signature, (a ->{| e} b) -> [a] ->{| e} [b], while a diagnostic about the same
function shows (a -> b) -> [a] -> [b]. They are the same function. Inference
replaces the row variable e with a fresh INTERNAL one, and an internal tail is
suppressed rather than printed, because it has no spelling a user could write
back into a file.