Effects

An effect is a typed signal that an expression needs help from its surrounding context—handling errors, missing values, state, and I/O with one mechanism:

• Errors and missing values — abort or supply a fallback (!div-by-zero, !parse-error, !null).

• Session state and configuration — read a value the UI or a caller can override (state).

• Files and host actions — read or write external data (!read, !write, !host, !stdin).

Handle and resume

handle intercepts one effect for the rest of the block.

Division by zero performs !div-by-zero. A handler may break the execution and return a value:

100

With resume, execution resumes from the effect-raising point:

101

An effect may carry a value. The handler names it after the effect:

32

The handler covers the remaining expressions in its block. When handlers are nested, the nearest matching one runs:

201

Common effects

• !div-by-zero comes from division by zero.

• !parse-error comes from parsing invalid text. Like !null, it cannot be resumed: the handler's value replaces the expression it handles.

• !null comes from using a missing optional value.

• !read and !write read and write files.

• !host asks the hosting web app to provide a capability.

• !stdin asks the command line app to provide input.

Effects that are not handled by the cell show as errors. Removing the => !div-by-zero part from the next line shows the error:

Nulls

Using a missing value performs !null: an empty optional where a plain value is required, or a position past the end of a list or table.

A !null handler cannot resume with a stand-in value; it replaces the whole handled expression:

0

or-else is syntactic sugar for that handler around its left side:

1

0

Like handle, or-else is lazy and only runs when a value is missing.

State

state creates an adjustable value with a default. Reading the name performs an effect named after that definition, which lets a handler substitute a temporary scenario value without changing the baseline.

120.00

200.00

A handler can also derive the scenario value from the default it receives:

200.00

Interactive UI controls are the same state declarations placed with input or field: state infers a control from the element type, and a decorator on the default, such as toggle, slider, or choice, picks one explicitly. See doc/ui.ki.

Effects in function types

A function type lists the effects the function may perform. Handling an effect removes it from the resulting function type.

:(fn int int -> int !div-by-zero)

:(fn int int -> int)

Custom effects

There is no fixed list of effect names. Performing !name creates a request that any surrounding handle !name may interpret.

107.00

Where next

• doc/program.ki — tasks, files, buttons, and host input