Coroutining & Resource Control¶
Clausal Prolog provides coroutining primitives for delayed goal execution and deterministic resource management. These predicates enable:
- Delayed goals — postpone execution until a variable is bound (
freeze/2,when/2) - Resource cleanup — guarantee cleanup runs regardless of success, failure, or exceptions (
setup_call_cleanup/3,call_cleanup/2; from 2.0 in.plmodules and the seam only, see below) - Solution control — count solutions efficiently (
count_all/2), or skip to the Nth solution (call_nth/2; from 2.0 in.plmodules and the seam only, see below)
Examples on this page are Clausal Prolog (.clausal), except the setup_call_cleanup/3, call_cleanup/2 and call_nth/2 ones, which are written in the seam. All predicates in this module are compiler special forms — they are compiled inline at compile time (like findall/3 and catch/3), and can be freely nested inside any other meta-predicate.
freeze/2¶
Delay Goal until variable X is bound.
- If
Xis already bound at the timefreezeis executed,Goalruns immediately. - If
Xis unbound,Goalis stored as an attributed variable attribute. WhenXis later unified with a value, the frozen goal is woken: it runs right after that unification, before the next goal, with every answer. If it fails, execution backtracks as if the unification had failed.
A woken goal backtracks like any other goal, as in Scryer:
f(Y) :- freeze(X, member(Y, [1, 2, 3])), X = go. % Y = 1 ; Y = 2 ; Y = 3
g(Y) :- freeze(X, member(Y, [1, 2, 3])), X = go, Y > 1. % Y = 2 ; Y = 3
Goals woken inside a test run inside it: X \= go (and, in a .pl module, \+ X = go) succeed when the goals X = go wakes have no answer, and memberchk/2 (ISO's once(member(...))) passes over an element whose woken goals fail and keeps the first answer of the rest.
As a builtin, append/3 unifies its whole known prefix as one unification, so the goals it wakes run after all of it rather than after each element. Scryer's clause-by-clause append/3 runs them after each element, so an impure woken goal can answer differently: freeze(X, Y == c), append([X, Y], R, [a, c, d]) answers R = [d] here and fails in Scryer. Pure goals give the same answers in both.
Multiple freezes on the same variable accumulate. All fire when the variable is bound. Backtracking undoes the attribute (the freeze is removed if the trail is unwound).
% Guard: X must be positive when bound
guarded(X) :-
freeze(X, X > 0),
X = 5.
% succeeds — 5 > 0
rejected(X) :-
freeze(X, X > 0),
X = -1.
% fails — the unification X = -1 is rejected because -1 > 0 fails
test("guarded") :-
guarded(X),
X == 5.
test("rejected", fail) :-
rejected(_).
% Deferred binding: the frozen goal Y = X fires when X is bound
deferred(Y) :-
freeze(X, Y = X),
X = "hello".
% Multiple freezes on the same variable
multi(Y, Z) :-
freeze(X, Y = X),
freeze(X, Z = X),
X = 42.
test("deferred") :-
deferred(Y),
Y == "hello".
test("multi") :-
multi(Y, Z),
Y == 42,
Z == 42.
Implementation
freeze uses the attributed variable hook infrastructure (the same mechanism used by dif/2, CLP(ℤ), and CLP(B)). The frozen goal is compiled as a closure (zero-arg generator factory) and stored under the "freeze" attribute key. When the variable is bound, the hook queues the goal on the trail (trail.push_pending); the engine runs the queue at the next goal boundary — after an inline unification or an inline comparison that can bind (the seam's CLP(ℤ) X == 3, X <= 3), at the start of a clause body whose head unified, and at every answer of a called predicate or builtin — once per answer. The queue and every change to it are trailed, so backtracking restores it.
A bare unify(...) called from Python with no driver owning the trail (trail.defer false) queues woken goals the same way, and runs the queue itself before it returns: after every hook of the unification has run, to the first answer. If the goals fail, the unification fails and binds nothing. Everything nested in that unification counts as part of it: a partial list or segment string unifying element by element, a hook that unifies, a woken goal that unifies. Those only queue, and the one drain runs their goals. Outside a driver, a when/2 whose condition already holds runs its goal at once, to its first answer, because no unification would ever run it.
Implementation: clausal/logic/compiler/control_constructs.py (_compile_freeze), clausal/logic/coroutining.py (_freeze_hook), clausal/logic/pending.py (the queue's drain)
when/2¶
Generalized coroutining: delay Goal until Condition is satisfied.
Supported conditions¶
| Condition | Meaning |
|---|---|
nonvar(X) |
X is bound (equivalent to freeze(X, Goal)) |
ground(X) |
X is fully ground (no unbound variables anywhere in X) |
(C1, C2) |
Conjunction: both C1 and C2 must be satisfied |
(C1 ; C2) |
Disjunction: either C1 or C2 suffices |
% equivalent to freeze(X, Goal)
test("when nonvar") :-
when(nonvar(X), Y = X),
X = 42,
Y == 42.
% Conjunction: fire when both X and Y are bound
test("when conjunction") :-
when((nonvar(X), nonvar(Y)), R = done),
X = 1,
var(R),
Y = 2,
R == done.
% ground: fire when term is fully ground
test("when ground") :-
when(ground([X, Y]), R = 'all ground'),
X = 1,
Y = 2,
R == 'all ground'.
How conditions decompose¶
when(nonvar(X), Goal)compiles directly asfreeze(X, Goal)— zero overhead.when((C1, C2), Goal)decomposes towhen(C1, when(C2, Goal))at run time — the inner when is installed when C1 is satisfied.when(ground(X), Goal)freezes on every unbound variable in X. when any is bound, groundness is re-checked. The goal fires when X is fully ground.when((C1 ; C2), Goal)attaches to variables in both conditions. Whichever fires first runs the goal (at most once).- A goal whose condition already holds runs at once, with every answer, like a woken
freezegoal; if it has none,when/2fails.
Implementation
Compile-time dispatch handles nonvar. Runtime helpers in clausal/logic/coroutining.py handle ground, conjunction and disjunction.
Implementation: clausal/logic/compiler/control_constructs.py (_compile_when), clausal/logic/coroutining.py (_install_when_ground, _install_when_disjunction, _install_when_condition)
Pending goals: printing them, frozen/2¶
A freeze/2 or when/2 still waiting when an answer is printed is shown as its goal, as Scryer shows it (operator ruling 2026-10-26), by clausal FILE -g GOAL and the ?- top level:
?- freeze(X, write(hi)).
freeze(X,write(hi)).
?- freeze(X, g), freeze(X, h).
freeze(X,(g,h)).
?- when((nonvar(X) ; ground(Y)), g).
when((nonvar(X);ground(Y)),g).
?- when(ground(f(X, Y)), g), X = 1.
X = 1, when(ground(f(1,Y)),g).
The form is plain: Scryer prints freeze:freeze(X,user:g), Clausal freeze(X,g), as it prints dif(X,a). Several freezes on one variable are one freeze/2 of their conjunction, in the order they were posted; a when/2 keeps its whole condition; when/2 goals on one variable come newest first. A delay whose variable is bound since, or a disjunction whose goal ran, is not shown.
Wake order follows Scryer's. When a variable is bound, its constraint hooks (dif/2, CLP) decide first; then its freeze/2 goals run, in posting order, and then its when/2 goals, newest first. Unifying two variables that both carry delays runs nothing: the goals are merged onto the surviving variable, those of the variable that got its first attribute first coming first, and run when it is bound. A variable aliased to one bound later in the same unification (f(X,Y) = f(Y,1)) has its goals run with that one's, after them.
frozen(@Term, -Goal) reads the same goals back as a term: the goals pending on the variables of Term, as one conjunction, or true when there are none (SWI's frozen/2; Scryer has none). Only freeze/2 and when/2 goals are listed, not dif/2 or CLP constraints.
From Python, clausal.logic.coroutining.pending_goals(variables) returns the list of goal terms.
Where Scryer answers differently¶
The differential fuzzer (tests/fuzz/scryer_diff.py, run under pytest from tests/fuzz/test_scryer_diff.py) runs random small goals over =/2, dif/2, freeze/2, when/2 and their neighbours in Clausal and in Scryer and compares every answer, residual and line of output. These differences are known, and the fuzzer accepts them:
- The order of the residual goals. Clausal prints an answer's
dif/2goals, then itsfreeze/2andwhen/2goals, each in the order of the answer's variables. Scryer's order follows its own attribute bookkeeping (freeze(B,g), dif(A,b)for the goaldif(A,b), freeze(B,g)). The goals are the same. - Scryer's
dif/2tries its unification with the frozen goals running. It binds the pair's variables to see whether they can be equal, and afreeze/2orwhen/2goal on one of them wakes during the try:freeze(A, write(a)), dif(A, f(B))printsain Scryer and nothing here; and a frozen goal that fails in the try makes Scryer drop thedif(freeze(A, A = 1), dif(A, f(B))shows nodif). Clausal's try wakes nothing; its answers are the same, with thedifkept until a binding decides it. - A
when/2on two variables that are then aliased is one delay here, and runs once, as in SWI-Prolog and SICStus; Scryer keeps a copy per variable and prints and runs it twice. Three aliased variables'freeze/2goals print as one conjunction nested to the left (((a,b),c)), whichever way the aliases are made. - Errors of
when/2namewhen/2as their context (error(domain_error(when_condition, C), when/2)); Scryer leaves the context unbound. ISO leaves the context implementation-defined. Neither system takes?=/2as a condition (SWI-Prolog does). - Scryer's
writeq/1of a term holding adif/2variable can name one variable two ways (f([_A|_B],_)forf([X|X],_);==/2says they are one). copy_term/2does not copyfreeze/2andwhen/2goals (Scryer copies every attribute incopy_term/2):todo/copy-term-attributes-freeze-clpz-and-copy-term-3-2026-09-30.md.copy_term/3hands them back as goals. Neither system'sfindall/3copies them.
Implementation
The goal term is not stored. Every delayed goal's thunk takes one optional argument: called with a true one, it returns its residual, ("freeze", key, Goal) or ("when", key, when(Cond, Goal)), built from the very variables it would run the goal over, and runs nothing (compiler/control_constructs._residual_goal_ast, coroutining.residual_of). The thunk is in the attribute, so the goal is trailed and undone with it, and installing or waking a delay costs what it did. copy_term/2 still does not copy a freeze attribute (todo/copy-term-attributes-freeze-clpz-and-copy-term-3-2026-09-30.md); the residual is what copy_term/3 hands back.
Residual goals: copy_term/3 and call_residue_vars/2¶
copy_term(+Term, -Copy, -Goals) copies Term to Copy with fresh variables that carry no attributes, and gives in Goals the goals that, called, put back on those variables the constraints Term's carry. call_residue_vars(:Goal, -Vars) calls Goal and, with each answer, gives the variables that got an attribute during it and still carry one, also those no argument of Goal reaches. Both are Scryer's (and SWI-Prolog's).
?- dif(X, a), copy_term(X, Y, Gs).
Gs = [dif(Y,a)], dif(X,a).
?- freeze(X, g), X in 1..3, copy_term(f(X, Z), C, Gs).
C = f(_A,_B), Gs = [_A in 1..3,freeze(_A,g)], X in 1..3, freeze(X,g).
?- {X >= 2}, copy_term(X, Y, Gs).
Gs = [{Y>=2}], {X >= 2}.
?- call_residue_vars((dif(Z, a), X = 1), Vs).
X = 1, Vs = [Z], dif(Z,a).
The goals are the ones -g and ?- print for the same constraints, in the same order, computed by the same function (clausal.logic.residuals): dif/2, then CLP(ℤ) domains and constraints (X in 1..3, X #< Y, all_different([X,Y])), then freeze/2 and when/2, then CLP(B) (sat(F) per network, F written with +, * and ~; a BDD node others share is spelled once, as a helper variable N with its own sat(N=:=F), so the goals stay linear in the BDD; a variable that is only Boolean is sat(X=:=X), as Scryer writes it), CLP(ℝ) (in_real(X, Lo, Hi), X #>= Lo, X #< Y), and CLP(Q) ({X >= 2}, the projection the toplevel shows). Only the variables of Term, and those their dif/2 and delayed goals reach, contribute: a constraint on another variable is not in Goals. A variable a goal shares with Term is Copy's; any other is fresh (dif(X, Z), copy_term(X, Y, Gs) gives Gs = [dif(Y,_A)]). A cyclic Term is copied as a cycle.
Calling the goals restores the constraints, so copy_term(T, C, Gs), maplist(call, Gs) copies T with them. Inside findall/3, which collects plain copies, the same goals keep each answer's constraints as data: findall(X-Gs, (dif(X, a), copy_term(X, X, Gs)), L) gives L = [_A-[dif(_A,a)]].
Where Scryer differs (tests/iso/test_copy_term_3_scryer.py holds the table):
- Scryer qualifies each goal with its library (
dif:dif(Y,a),clpz:(Y in 1..3)); Clausal's are plain, as its printers' are. - CLP(ℤ) goals are Clausal's own forms (
X #< Y,scalar_product([1,-1,-1],[X,A,B],#=,0)), not Scryer's (X#=<Y+ -1,A+B#=X). - CLP(B) goals are a formula of the BDD (
sat(X* ~(Y)+ ~(X)*Y)), not Scryer's algebraic normal form (sat(X=\=Y)). - CLP(Q) goals are
{}/1goals, which{}/1reads back; Scryer's library(clpq) gives the bare relation (Y>=2), and loses an equation ({X + Z = 3}, copy_term(X-Z, Y, Gs)givesGs = []). Scryer ships no CLP(ℝ) of Clausal's kind; there the toplevel's output is the reference. call_residue_vars/2does not list the internal variables Scryer's library(clpb) and library(clpq) create (call_residue_vars(sat(A+B), Vs): ScryerVs = [A,B,_A], ClausalVs = [A,B]).- The order of the goals is the printers' (dif, CLP(ℤ), freeze/when), not Scryer's.
copy_term/2 still copies only dif/2 (todo/copy-term-attributes-freeze-clpz-and-copy-term-3-2026-09-30.md), and findall/3 copies no attribute (todo/findall-drops-dif-and-clpz-constraints-2026-11-04.md, as Scryer).
setup_call_cleanup/3¶
Deterministic resource management — the logic programming equivalent of try/finally.
- Setup runs first (must succeed deterministically; only the first solution is taken).
- Call runs normally (may succeed zero or more times, fail, or throw).
- Cleanup runs exactly once, regardless of how Call terminates:
- After all solutions of Call have been enumerated
- If Call fails (Cleanup runs, then the whole goal fails)
- If Call throws an exception (Cleanup runs, then the exception is re-raised)
If Setup fails, the whole goal fails and Cleanup does not run.
Refused in Clausal Prolog from 2.0
Setup runs as once/1, and Cleanup runs once, at a time only the
execution decides (after the last answer, on failure, or on a ball):
committed choice, which gives up monotonicity. From release 2.0, Clausal
Prolog (.clausal) refuses setup_call_cleanup/3 and call_cleanup/2
as it refuses \+/1, once/1, forall/2 and call_nth/2 (operator
ruling 2026-11-28): a module that calls one does not load, with
"setup_call_cleanup/3 (committed choice) is not provided in Clausal
Prolog; write dif/2, if_/3 or a deterministic predicate, or put the code
in a .pl module, which runs it as ISO", and a goal built and called at
run time raises error(existence_error(procedure,
setup_call_cleanup/3), _). Both are kept in a .pl (full ISO) module
and in the seam, where the examples below are written. A
Clausal Prolog program has no resources of its own to release (no ISO
streams, no Python handles); a resource is acquired and released in the
seam, which calls Python.
The example takes and releases a lock fact. (Setup can also open a Python
file handle, HANDLE is ++open(PATH), and Cleanup close it,
++HANDLE.close().)
# Basic pattern: acquire, use, release
with_lock(GOAL) <- setup_call_cleanup(
assertz(held('lock')),
call(GOAL),
retract(held('lock')),
)
# Cleanup runs once Call has no more solutions, so enumerate them all:
test("cleanup releases the lock") <- (
findall(L, with_lock(held(L)), LS),
LS is ['lock'],
findall(L2, held(L2), []),
)
# Call fails: Cleanup still runs, overall fails
test("scc call fails", fail) <- with_lock(member(X_UNUSED, []))
test("the lock is released after a failure") <- (
findall(1, with_lock(member(X_UNUSED, [])), []),
findall(L, held(L), []),
)
call_cleanup/2¶
Sugar for setup_call_cleanup(true, Call, Cleanup) — no setup step, just guaranteed cleanup. Refused in Clausal Prolog from 2.0 with setup_call_cleanup/3 (above); the example is the seam's.
safe_query(GOAL) <- call_cleanup(
call(GOAL),
(write('query finished'), nl),
)
test("safe query") <- (
safe_query(member(X, [1])),
X is 1,
)
call_nth/2¶
Call Goal and succeed only on the Nth solution. The first N-1 solutions are skipped.
Refused in Clausal Prolog from 2.0
call_nth(Goal, 1) is once(Goal): committed choice, which gives up
monotonicity. From release 2.0, Clausal Prolog (.clausal) refuses
call_nth/2 as it refuses once/1, \+/1, forall/2,
setup_call_cleanup/3 and call_cleanup/2 (operator rulings
2026-11-28): a module that calls it does not load, with
"call_nth/2 (committed choice) is not provided in Clausal Prolog; write
dif/2, if_/3 or a deterministic predicate, or put the code in a .pl
module, which runs it as ISO", and a goal built and called at run time
raises error(existence_error(procedure, call_nth/2), _). It is kept in
a .pl (full ISO) module and in the seam, where the
examples below are written. In Clausal Prolog, collect the answers with
findall/3 and take the Nth with nth1/3, or write the predicate so
that the answer you want is the one it gives.
Nmust be a positive integer (>= 1). Anything else, an unboundNincluded, raiseserror(type_error(positive_integer, N), call_nth/2)(the Scryer error form; see Exceptions).Ndoes not enumerate.- If Goal has fewer than N solutions,
call_nthfails. - Only the Nth solution's bindings are visible to the continuation.
# Get the 3rd member
test("third") <- (
call_nth(in_(X, [10, 20, 30, 40, 50]), 3),
X is 30,
)
# N exceeds available solutions: fails
test("too few", fail) <- call_nth(in_(X_UNUSED, [1, 2]), 5)
count_all/2¶
Count the number of solutions of Goal without collecting them. Unifies Count with the integer result.
Unlike findall + length, count_all does not build a list — it just counts. Bindings from the inner goal are not visible after counting (the trail is unwound).
% Count members
test("count") :-
count_all(in_(_, [a, b, c, d]), N),
N == 4.
% No solutions — 0
test("empty") :-
count_all(in_(_, []), N),
N == 0.
% With filter
test("filtered") :-
count_all((in_(X, [1, 2, 3, 4, 5]), X > 3), N),
N == 2.
Inside a hook or at a goal¶
For constraint-library authors. An attribute hook runs while the unification that bound its variable is still firing hooks; a goal runs at a goal boundary. Under a driver trail.defer is true in both places, so it cannot tell them apart. trail.hooks_running can:
| Where | trail.defer |
trail.hooks_running |
|---|---|---|
| A goal under a driver (a body goal, a woken goal) | True |
0 |
A woken goal that a bare unify runs itself |
True |
0 |
| Python code outside any driver or unification | False |
0 |
| Inside an attribute hook, under a driver or not | True |
1 |
| Inside a hook of a unification nested in a hook | True |
2, one more per level |
The contract:
- Inside a hook (
hooks_running > 0) a library must not post a constraint in place, must not run another library's entry point, and must not drive a goal on the trail. It queues the work as a goal withtrail.push_pending(goal), and the goal runs at the next goal boundary, after every hook of the unification has run.solve(..., trail=t)andcall(..., trail=t)on a trail whose hooks are running raise the ISO-shapederror(permission_error(call, goal, Goal), Context): Context issolve/2forsolve, andcall/Nforcall(F, A1, ..., Ak), where N = k + 1 and Goal isF(A1, ..., Ak), or the atomFwhen k = 0 (socall("p", X, trail=t)reportscall/2and the goalp(X), andcall("p", trail=t)reportscall/1and the goalp). A driver on a different, fresh trail is allowed, with a caveat: its bindings are on ITS trail, not the outer one. If it binds a variable of the outer computation and the hook keeps that binding (it takes the first answer and stops), an undo of the outer trail does not undo it: the outer unification is undone and the variable stays bound. Bind outer variables only through the hook's own trail (by unifying on it), or queue the goal. - At a goal (
hooks_running == 0) a library may post in place. A binding it makes wakes goals, which run at the goal boundary that follows, before the next goal and with every answer. In compiled code that boundary comes after every unification, every inline comparison that can bind (the seam's CLP(ℤ)X == 3,X <= 3, and the posts of a reified test inif_/3), and every answer of a call. A goal that ends in such an op inside a construct with a scope of its own (catch/3,findall/3,\+,once/1,forall/2,call_cleanup/2,setup_call_cleanup/3) runs what it woke inside that scope, socatch/3catches a ball thrown by a woken goal. A goal woken by a binding AFTER thecatch/3runs outside it, and its ball escapes the catch (ISO 7.8.9).
The counter goes up when a unification starts dispatching the hooks of the attributed variables it bound, and back down when that dispatch ends, whether it succeeds, a hook fails, or a hook raises (KeyboardInterrupt and RecursionError included). Woken goals that a bare unify runs itself (to their first answer) run after its dispatch has ended, so they see 0. The counter is read-only. C extensions read the hooks_running field of TrailObject from _variables_capi.h.
On any trail: hook_dispatch_depth()¶
trail.hooks_running counts one trail's dispatches. A hook that builds a fresh Trail() and calls a library on it sees 0 on that trail, although it is still inside a hook. clausal.logic.variables.hook_dispatch_depth() counts the dispatches in progress in the calling thread, on every trail:
| Where | trail.hooks_running |
hook_dispatch_depth() |
|---|---|---|
| A goal (under a driver or not) | 0 |
0 |
| Inside a hook | 1 |
1 |
| Inside a hook, on a fresh trail the hook built | 0 (the fresh trail's) |
1 |
| Inside a hook of a unification on that fresh trail | 1 (the fresh trail's) |
2 |
It goes up and down with trail.hooks_running, in the same place and on the same exit paths. It is thread-local: a hook running in another thread does not count. It is read-only. C extensions call the hook_dispatch_depth entry of the _C_API capsule (_variables_capi.h).
The contract:
- A library entry point that must not run inside a hook refuses, or queues its work, when either count is above zero:
trail.hooks_runningon the trail it was given, orhook_dispatch_depth(). Checking only the trail it was handed lets a hook bypass the rule with a fresh trail. solve()andcall()still refuse only on the same trail (trail.hooks_running > 0). A driver on a fresh trail inside a hook stays allowed, with the caveat above; inside it,hook_dispatch_depth()is above zero, so the libraries it calls can tell where they are.
Implementation: clausal/logic/variables/_variables.c (fire_wakeups, Trail.hooks_running, hook_dispatch_depth)
Nesting inside meta-predicates¶
All of these are compiler special forms that compile their goal arguments inline. They nest freely inside other meta-predicates — findall, catch, and each other (and, in a .pl module or the seam, once and forall, which Clausal Prolog refuses from 2.0, as it refuses call_nth/2, setup_call_cleanup/3 and call_cleanup/2):
% (call_nth/2, setup_call_cleanup/3 and call_cleanup/2 are refused in Clausal
% Prolog from 2.0, operator rulings 2026-11-28; their nesting examples are
% in the seam fixtures.)
% findall wrapping when
test("findall+when") :-
findall(Y, (when(nonvar(X), Y = X), X = 7), BAG),
BAG == [7].
% catch wrapping count_all whose goal throws
test("catch+countall") :-
catch(
count_all(throw(oops), _),
oops,
R = caught
),
R == caught.
% freeze inside findall
test("findall+freeze") :-
findall(
Y,
(freeze(X, Y = X), X = 99),
BAG
),
BAG == [99].
% count_all inside findall
test("findall+countall") :-
findall(
N,
count_all(in_(_, [a, b, c]), N),
BAG
),
BAG == [3].
and the cleanup pair and call_nth/2, in the seam:
# findall wrapping call_cleanup
test("findall+call_cleanup") <- (
findall(X, call_cleanup(in_(X, [10, 20, 30]), True), BAG),
BAG is [10, 20, 30],
)
# setup_call_cleanup inside catch: the cleanup runs, then the ball is re-raised
test("catch+scc") <- (
catch(setup_call_cleanup(True, throw('oops'), assertz(held('cleaned'))),
'oops', R is 'caught'),
R is 'caught',
retract(held('cleaned')),
)
# findall wrapping call_nth
test("findall+callnth") <- (
findall(X, call_nth(in_(X, [10, 20, 30]), 2), BAG),
BAG is [20],
)
# catch wrapping call_nth with bad N
test("catch+callnth") <- (
catch(call_nth(in_(X_UNUSED, [1, 2, 3]), 0), ERROR_UNUSED, R is 'caught'),
R is 'caught',
)
Test coverage
Tests are in tests/test_coroutining.py (51 tests) and
tests/fixtures/coroutining.seam (20 tests); this page's examples are
tests/fixtures/docs/coroutining_examples.clausal (13 tests) and, for
the constructs Clausal Prolog refuses from 2.0,
tests/fixtures/docs/coroutining_example_cleanup.seam (6 tests) and
tests/fixtures/docs/coroutining_example_call_nth.seam (4 tests).
- call_nth: basic, first/last, too few solutions, N as variable, zero/negative/non-integer raises, fail goal, single solution
- count_all: basic, empty, large range, already-bound correct/wrong, with filter, no side effects
- setup_call_cleanup: basic, call succeeds, call fails (cleanup runs), call throws (cleanup runs, re-raised), setup fails (no cleanup)
- call_cleanup: basic, call fails, call throws, with solutions
- freeze: already bound, deferred, goal success/failure, multiple on same var, backtracking removes attr
- when: nonvar already/deferred, conjunction full/partial, ground already/deferred/nested, goal failure
- Meta-predicate nesting: findall+call_nth, findall+count_all, once+call_nth, once+count_all, catch+call_nth, call_nth inside freeze, SCC inside findall, freeze inside findall, count_all inside count_all, call_cleanup inside once
See also: Builtins — for the complete predicate index, Exceptions — for throw/catch, Constraints — dif/2 and CLP(ℤ) use the same attributed variable mechanism.