Clausal Prolog Predicate Index¶
Complete index of all built-in and standard-library predicates. Predicates are listed as Name/arity.
Behaviour follows ISO 13211-1 first, and Scryer Prolog where ISO is silent. Error terms are Scryer's error(Formal, Culprit); see Exceptions. Which of these the 1.0 release covers is set out in Public API.
Documented on their own pages, not here: the ISO comparison builtins are summarised below and in Operators; is_chars/1, is_codes/1 in Type checking; time_goal/1 and call_with_time_limit/2 in Control; has_units/2, quantity/… in Units; rational/1 and rdiv in Arithmetic; CLP(ℚ)/CLP(ℝ) (in_q, in_real, label_real, minimize, maximize, inf, sup, bb_inf, entailed, dump_q, …) in CLP(ℚ) and CLP(ℝ); and the solver packages (z3.*, ortools.*, pysat.*) in their own pages.
Notation in signature lines:
- + = must be bound (input)
- - = output (unified with result)
- ? = either input or output
Signatures and examples on this page are Clausal Prolog
(.clausal): ISO Prolog syntax, without cut. The seam,
Clausal's Python-syntax surface, calls the same builtins; where it spells
one differently, or where an entry works only from the seam, the entry says
so.
The ISO built-ins are static (ISO 7.5.1). A .pl or .clausal file
that defines a clause for one (atom_length(_, 5)., once(G) :- ..., a
grammar rule atom_length --> []), or declares one dynamic, is refused at
load with permission_error(modify, static_procedure, Name/Arity), as
Scryer refuses it; assertz/asserta/retract of one raise the same
error at run time. The ISO built-ins are the control constructs and the
predicates of ISO 13211-1 clause 8 (clausal/tools/iso_builtins.py). The
library predicates on this page (append/3, length/2, between/3,
forall/2, msort/2, numbervars/3, ...) are no ISO built-ins, and a file
may define its own. A seam module is not ISO text and is not checked.
Builtin term constructors (Python)
Every builtin with a Python-identifier name is also an object on the
clausal module (clausal.append, clausal.between, ...). Calling it
builds a cell -- the plain tuple (functor, *args), exactly what
make_cell builds; it runs nothing:
import clausal
from clausal import Var, Module, make_cell, solve
Z = Var()
clausal.append([1, 2], [3, 4], Z) # ('append', [1, 2], [3, 4], Z)
make_cell("append", [1, 2], [3, 4], Z) # the same cell
clausal.between(low=1, high=10, x=Z) # keywords name a registered arity's fields
clausal.between(1, 10) # ('between', 1, 10): built as written, never padded
clausal.nl() # 'nl': a 0-arity builtin builds its atom
X = Var()
for _ in solve(clausal.between(1, 3, X), module=Module("scratch")):
print(X.value) # 1, 2, 3
solve needs module= even for a builtin goal: a cell carries no module
of its own. Inside a .seam file, query with the goal-position seam
instead (for X in --between(1, 3, X): ...; see
Python integration). The objects are covered as
predicates, not as Python objects; see Public API.
get_builtin_class(name) still returns them but is internal.
Passing builtins to higher-order predicates. A builtin's name is a
goal: pass it straight to maplist, include, exclude, foldl,
call/N, ... with no lambda wrapper:
all_numbers(XS) :- maplist(number, XS).
keep_ints(XS, INTS) :- include(integer, XS, INTS).
incremented(XS, YS) :- maplist(succ, XS, YS).
test("builtins as goals") :-
all_numbers([1, 2.5]),
keep_ints([1, a, 2], [1, 2]),
incremented([1, 2], [2, 3]).
Summary¶
| Category | Predicates |
|---|---|
| Control Flow | once/1 and \+ (seam not), setup_call_cleanup/3 and call_cleanup/2 (all four refused in Clausal Prolog from 2.0), if_/3, throw/1, catch_recover/3, catch/3, halt/0,1, repeat/0 |
| Coroutining | freeze/2, when/2, frozen/2, call_residue_vars/2 |
| Meta-Predicates | findall/3,4, bagof/3, setof/3, forall/2 and call_nth/2 (both refused in Clausal Prolog from 2.0), count_all/2 |
| Higher-Order Call | call/1..8, call_goal/1..8 |
| DCG (Definite Clause Grammars) | phrase/2, phrase/3 |
| Term Inspection | functor/3, arg/3, unpack/2, copy_term/2, copy_term/3, term_variables/2, numbervars/3, gensym/2, module_constant/3 |
| Runtime Database | assertz/1, asserta/1, retract/1, clause/2, abolish_table/2, abolish_all_tables/0 |
| Prolog Flags | set_prolog_flag/2, current_prolog_flag/2, char_conversion/2, current_char_conversion/2 |
| Operators | op/3, current_op/3 |
| Keyword-Term Introspection | vary/3, unbound_keys/2, signature/3 |
| Attributed Variables | put_attr/3, get_attr/3, del_attr/2, get_attrs/2, put_attrs/2, attvar/1, term_attvars/2 |
| Constraint Predicates | dif/2, eq/3, dif_t/3, =/3, dif/3 |
| CLP(ℤ) — Integer Constraints | in_domain/3, label/1, all_different/1, structural_eq/2, sum_/3, scalar_product/4, element/3, circuit/1 |
| CLP(B) — Boolean Constraints | sat/1, taut/2, sat_count/2, bool_labeling/1 |
| Type Checks | var/1, nonvar/1, atom/1, string/1, is_str/1, atomic/1, number/1, integer/1, float_/1, compound/1, callable_/1, is_list/1, ground/1, must_be/2, can_be/2 |
| Dict and Set Predicates | get/3,4, get_strict/3, tri_get/3, delete/3, is_dict/1, is_dict_t/2, dict_get/3, dict_put/4, dict_merge/3, gen_dict/3, sub_dict/2, is_set/1, set_union/3, set_subset/2, gen_set/2 |
| Arithmetic | between/3, succ/2, plus/3, abs_/2, max_/3, min_/3, sign/2, gcd/3, divmod_/4, lcm/3, exp_mod/4, popcount/2, msb/2, lsb/2 |
| List Predicates | in_/2, append/3, length/2, reverse/2, sort/2, sort/4, permutation/2, select/3, flatten/2, take/3, drop/3, zip_/3, map_list_to_pairs/3, split_with/3, numlist/2,3, same_length/2, transpose/2 |
| Higher-Order List Predicates | maplist/2..9, include/3, exclude/3, partition/4, tfilter/3, tpartition/4, foldl/4,5,6, take_while/3, drop_while/3, span/4, group_by/3, sort_by/3, predsort/3, filter_map/3 |
| Character/String | char_type/2, char_code/2, upcase_atom/2, downcase_atom/2, atom_length/2, atom_chars/2, atom_codes/2, atom_concat/3, sub_atom/5, number_chars/2, number_codes/2, atom_string/2 |
| I/O | write/1, writeq/1, print/1, write_canonical/1, write_term/2, writeln/1, write_text/1, writeln_text/1, print_term/1, nl/0, tab/1, write_to_string/2, write_text_to_string/2, term_to_string/2, term_to_atom/2, atom_to_term/3, listing/1, portray_clause/1 |
Logging (log module) |
get_logger, debug, info, warning, error, critical, log, set_level, get_level, stream_handler, file_handler |
Date & Time (date_time module) |
now, now_utc, today, date, time, datetime, timedelta, date_add, date_sub, date_diff, datetime_string, timestamp, datetime_string_iso, date_string_iso, date_of, days_between, weekday, date_between, date_max, date_min, ordinal |
| Time & statistics | current_time/1, statistics/2 |
| ISO comparison and term order | '='/2, '\\='/2, '=='/2, '\\=='/2, '@<'/2 ..., compare/3, '=..'/2, 'is'/2, '=:='/2, '<'/2 ... |
| Operator Syntax (Compiler Special Forms) | the seam's is, is not, ==, !=, <, <=, >, >=, in, not in, not |
| Solver packages | z3.*, ortools.*, pysat.*, clpq.*, clpr.*: see their own pages (Constraints) |
Control Flow¶
These are compiler special forms — transformed at compile time, not dispatched via the builtin registry.
once/1¶
Commit to the first solution of Goal; succeeds at most once even if Goal has multiple solutions. It gives up monotonicity. Refused in Clausal Prolog from 2.0 (operator ruling 2026-11-28), like !, -> and *->: a .clausal body that uses it does not load, and a goal built and called at run time (call/N, the goal of findall/3, -g) throws error(existence_error(procedure, once/1), _). It remains in a .pl (full ISO) module, the seam and the Python API. In Clausal Prolog, write a deterministic predicate, or if_/3 with a reifiable condition (see Control).
Implementation & tests
Seam tests: tests/fixtures/once_member.seam
Python tests: tests/test_builtins.py
not/1¶
Negation as failure (NAF). Succeeds if Goal has no solutions; not monotone. ISO writes it \+ Goal, and the seam writes it as the Python keyword, not goal, in a clause body. Clausal Prolog has neither: there is no not/1 (calling it is existence_error(procedure, not/1)), and from 2.0 \+/1 is refused (operator ruling 2026-11-28), like !, -> and *->: a .clausal body that uses it does not load, and a goal built and called at run time (call/N, the goal of findall/3, -g) throws error(existence_error(procedure, (\+)/1), _). It remains in a .pl (full ISO) module, the seam (not) and the Python API. In Clausal Prolog, write dif/2 for \+ X = Y, if_/3 with a reified condition, or a deterministic predicate; a test that a goal fails is test(Name, fail) :- Goal.
For tabled predicates, uses well-founded semantics (delayed negation); see WFS.
Implementation & tests
Seam tests: tests/fixtures/wfs_win.seam, tests/fixtures/wfs_win_asym.seam
Python tests: tests/test_compiled_programs.py, tests/test_wfs.py
if_/3 (If-Then-Else)¶
The reified if-then-else, library(reif)'s if_/3 (see Reified if-then-else); Clausal Prolog has no cut and no ->. A .clausal file loads it with :- use_module(library(reif)). (without it, if_/3 is existence_error(procedure, if_/3)), and a written if_ goal is compiled where it is written. The import also defines if_/3 as a predicate with the same meaning, so a goal built at run time reaches it too: call(if_(...)), G = if_(...), G, call(if_, C, T, E) and a lambda body. Cond must be reifiable: X = Y (library(reif)'s =/3), dif(X, Y) (dif/3), a conjunction (C1, C2) or disjunction (C1 ; C2) of them, or a closure called with the truth value appended (memberd_t(E, Es) runs memberd_t(E, Es, T)). With X unbound, if_(X = 1, ...) explores both branches, the Else branch under dif(X, 1); a closure's every answer is explored. A plain goal as the condition is called with the truth value appended, so if_(atom(X), ...) raises existence_error(procedure, atom/2). Of the comparisons, clpz's reified X #= Y and X #< Y (#=/3, #</3, the two Scryer's clpz exports) are conditions; X >= Y, X #> Y and the rest name no procedure (existence_error(procedure, (>=)/3)), as in Scryer. The seam also reifies its comparisons (X is 1, X is not Y, ==, !=, <, <=, >, >=), and refuses a plain goal (if_(in_(Y, [1, 2]), ...), if_(atom(X), ...)) at load time -- it used to run as a soft cut, which is not monotone (ruling 2026-10-01).
Implementation & tests
Seam tests: tests/fixtures/reified_memberd.seam, tests/fixtures/tabled_ite.seam, tests/fixtures/reified_max.seam
Python tests: tests/test_reified_ite.py, tests/iso_l3/test_seam_if_requires_reifiable.py
throw/1¶
Raise a logic-level exception carrying Term. The exception propagates through the generator/trampoline chain until caught by catch/3 or surfaces as a Python LogicException.
Implementation & tests
Exception class: clausal/logic/exceptions.py (LogicException)
Seam tests: tests/clausal_modules/exceptions.seam
Python tests: tests/test_exceptions.py
catch_recover/3¶
Execute Goal. If it throws and the thrown term unifies with Error, execute Recovery. It never re-raises: a thrown term that does not unify with Error makes catch_recover fail. For ISO behaviour (re-raise on mismatch) use catch/3.
Implementation & tests
catch/3¶
Execute Goal. If Goal throws, unify the thrown term with Catcher. If unification succeeds, execute Recovery; otherwise re-raise. If Goal succeeds without throwing, catch/3 is transparent — all solutions pass through.
An ISO error arrives in Scryer's form, error(Formal, Culprit), where Culprit is the predicate indicator (catch(atom_length(1, _), E, true) binds E = error(type_error(atom, 1), atom_length/2)); see Exceptions. A Python exception raised inside Goal (by a builtin's implementation, for example) is caught as the term ClassName(Message), from Clausal Prolog and the seam alike. In the seam, where ++expr runs Python, catch(++int("x"), E, true) binds E to the cell ('ValueError', "invalid literal for int() with base 10: 'x'"). Bindings made by the failing goal are undone before recovery runs.
Implementation & tests
Seam tests: tests/clausal_modules/exceptions.seam
Python tests: tests/test_exceptions.py
halt/0, halt/1¶
Terminate execution by raising SystemExit. halt/0 exits with code 0; halt/1 exits with the given code. catch/3 does not absorb it.
A 0-arity predicate in goal position is written bare, as in ISO Prolog — halt, nl, abolish_all_tables, true, fail, false. (The seam also accepts parentheses, halt(), nl(); in a .clausal file nl() is not a call.)
Implementation & tests
Python tests: tests/test_exceptions.py
repeat/0¶
ISO 8.15.3: succeeds, and succeeds again on every backtrack, forever. It is an endless disjunction of true, which is monotone, so it is available on every surface. Bound it with a goal after it that eventually succeeds (in a .pl module or the seam, also with once/1 or call_nth/2). It binds nothing, so each retry uses no trail and no Python stack. A registered builtin, not a special form.
Implementation & tests
Python tests: tests/iso/test_repeat_between_bounds_scryer.py (rows checked against Scryer and Trealla, and a 200000-retry run in bounded space)
setup_call_cleanup/3¶
Deterministic resource management (try/finally for logic). Setup runs once (first solution only). Call runs normally. Cleanup runs exactly once regardless of how Call terminates — success, failure, or exception. If Setup fails, Cleanup does not run. Setup is once/1, and Cleanup runs at a time only the execution decides: committed choice, which gives up monotonicity. Refused in Clausal Prolog from 2.0 (operator ruling 2026-11-28), like once/1: a .clausal body that uses it does not load, and a goal built and called at run time (call/N, the goal of findall/3, -g) throws error(existence_error(procedure, setup_call_cleanup/3), _). It remains in a .pl (full ISO) module, the seam and the Python API (see Coroutining).
Implementation & tests
Python tests: tests/test_coroutining.py::TestSetupCallCleanup
Seam tests: tests/fixtures/coroutining.seam
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 (operator ruling 2026-11-28): a .clausal body that uses it does not load, and a goal built and called at run time throws error(existence_error(procedure, call_cleanup/2), _). It remains in a .pl (full ISO) module, the seam and the Python API.
Implementation & tests
Python tests: tests/test_coroutining.py::TestCallCleanup
Seam tests: tests/fixtures/coroutining.seam
Coroutining¶
Coroutining predicates delay goal execution until variables are bound. They use the attributed variable hook infrastructure.
Full documentation: Coroutining
freeze/2¶
Delay Goal until X is bound. If X is already bound, runs Goal immediately. If X is unbound, attaches Goal as an attribute; when X is later unified, the frozen goal fires synchronously — failure rejects the unification.
Implementation & tests
Python tests: tests/test_coroutining.py::TestFreeze
Seam tests: tests/fixtures/coroutining.seam
when/2¶
Generalized coroutining: delay Goal until Condition is satisfied. Supported conditions: nonvar(X), ground(X), conjunction (C1, C2), disjunction (C1 ; C2).
Implementation & tests
Python tests: tests/test_coroutining.py::TestWhen
Seam tests: tests/fixtures/coroutining.seam
frozen/2¶
Goal is the freeze/2 and when/2 goals pending on the variables of Term, as one conjunction, or true when there are none: freeze(X, g), frozen(X, G) gives G = freeze(X,g). SWI's frozen/2, in plain form (no module qualifiers), and listing only freeze/2 and when/2 goals. The same goals are what -g and ?- print for an answer.
Implementation & tests
Python tests: tests/test_freeze_when_residual_goals.py, tests/iso/test_freeze_when_residuals_scryer.py
call_residue_vars/2¶
Call Goal; with each of its answers, Vars is the list of the variables that got an attribute during Goal (a dif/2, a CLP domain or constraint, a freeze/2 or when/2 goal) and still carry one, unbound, in the order they got their first one. A variable no argument of Goal reaches is listed too: call_residue_vars((dif(Z, a), X = 1), Vs) gives Vs = [Z]. Scryer's and SWI's call_residue_vars/2; see Coroutining.
Implementation & tests
Implementation: clausal/logic/builtins/control.py, clausal/logic/residuals.py
Tests: tests/iso/test_copy_term_3_scryer.py, tests/fixtures/copy_term_3.clausal, tests/fixtures/copy_term_3.seam
Meta-Predicates¶
These are compiler special forms recognized by name in compile_goal/compile_goal_trampoline. Inner goals compile in simple mode as sub-generators.
findall/3¶
Collect all bindings of Template produced by Goal into Bag (a list). Succeeds with [] if Goal has no solutions.
Implementation & tests
Seam tests: tests/fixtures/meta_test.seam
Python tests: tests/test_meta.py
findall/4¶
findall(Template, Goal, Bag, Tail): as findall/3, but the collected list
ends in Tail instead of [] (Scryer's difference-list form):
findall(X, member(X, [1, 2]), L, [3]) gives L = [1, 2, 3]. Bag and
Tail must each be a list or a partial list (type_error(list, _)).
Implementation & tests
Python tests: tests/iso_l3/test_l3_s4_constructs.py
bagof/3¶
Like findall/3 but fails if Goal has no solutions, and collects one bag
per binding of the goal's free variables (those in neither Template nor a
leading Var ^), backtracking over the bags in the standard order of those
bindings (ISO 8.10.2). A bag preserves duplicate solutions. See
Meta-Predicates.
Implementation & tests
Seam tests: tests/fixtures/meta_test.seam
Python tests: tests/test_meta.py
setof/3¶
Like bagof/3 (one set per binding of the free variables, ^ for
existential ones) but removes duplicates and sorts each set.
Implementation & tests
Seam tests: tests/fixtures/meta_test.seam
Python tests: tests/test_meta.py
forall/2¶
Universal quantification: succeeds if Action succeeds for every solution of Cond. Desugars to \+ (Cond, \+ Action), so it is negation as failure underneath. Refused in Clausal Prolog from 2.0 (operator ruling 2026-11-28), like !, -> and *->: a .clausal body that uses it does not load, and a goal built and called at run time (call/N, the goal of findall/3, -g) throws error(existence_error(procedure, forall/2), _). It remains in a .pl (full ISO) module, the seam and the Python API. In Clausal Prolog, collect and check: findall(X, Cond, Xs), maplist(Check, Xs), or maplist/2 over the list directly (see Meta-Predicates).
Implementation & tests
Seam tests: tests/fixtures/meta_test.seam
Python tests: tests/test_meta.py
call_nth/2¶
Call Goal and succeed only on the Nth solution (1-indexed). Skips the first N-1 solutions. Fails if Goal has fewer than N solutions. Raises type_error if N is not a positive integer. call_nth(Goal, 1) is once(Goal), so it is committed choice and gives up monotonicity. Refused in Clausal Prolog from 2.0 (operator ruling 2026-11-28), like once/1: a .clausal body that uses it does not load, and a goal built and called at run time (call/N, the goal of findall/3, -g) throws error(existence_error(procedure, call_nth/2), _). It remains in a .pl (full ISO) module, the seam and the Python API (see Coroutining).
Implementation & tests
Python tests: tests/test_coroutining.py::TestCallNth
Seam tests: tests/fixtures/coroutining.seam
count_all/2¶
Count the number of solutions of Goal without collecting them. Unifies Count with the integer result. Bindings from the inner goal are not visible after counting (the trail is unwound).
Implementation & tests
Python tests: tests/test_coroutining.py::TestCountAll
Seam tests: tests/fixtures/coroutining.seam
Time & statistics¶
current_time/1¶
Unify T with the current Unix timestamp as a float (seconds since epoch).
statistics/2¶
Query runtime statistics. With Key bound, looks up a specific stat. With Key unbound, enumerates all available stats via backtracking.
| Key | Value |
|---|---|
wall_time |
Wall-clock seconds since process start (float) |
cpu_time |
CPU seconds used by this process (float) |
memory |
Peak RSS memory in bytes (int, Linux/macOS only) |
Higher-Order Call¶
call/1..8¶
Call Goal (a lambda or dispatch function) with 0–7 extra arguments appended. Aliases for call_goal/1..8.
Implementation & tests
Seam tests: tests/fixtures/builtins_call.seam
Python tests: tests/test_meta.py, tests/test_higher_order.py
call_goal/1, call_goal/2, call_goal/3¶
Core implementation of higher-order call. Goal must be a callable (lambda or _get_dispatch() object). call_goal/4..8 are generated via _make_call_goal_n.
Implementation & tests
Seam tests: tests/fixtures/builtins_call.seam
Python tests: tests/test_meta.py, tests/test_higher_order.py
DCG (Definite Clause Grammars)¶
phrase/2¶
Invoke a DCG rule and require it to consume the entire input list. RuleBody is either a predicate name (0 extra args, e.g. greeting) or a partial term (N extra args, e.g. digit(D)). equivalent to calling the rule with List as the input state and [] as the output state. A RuleBody built at run time as a control construct is a DCG body, as in ISO: the conjunction ','(A, B), the disjunctions ';'(A, B) and '|'(A, B), and '\+'(A), with lists and strings inside them as terminals — G =.. [',', inc, inc], phrase(G, [0], [N]). In a .clausal file, (inc, inc) written in source is that same conjunction, so phrase((inc, inc), [0], [N]) works too. (In the seam, (inc, inc) written in source is the compound inc(inc), not a conjunction.)
Implementation & tests
Python tests: tests/test_dcg.py
phrase/3¶
Invoke a DCG rule for partial parsing. Like phrase/2, but the remaining unconsumed input is unified with Rest instead of requiring [].
Also used for state-passing DCGs: encode state as a single-element list [State], thread it through DCG nonterminals using phrase(Rule, [InitialState], [FinalState]). See DCGs — state threading for the full pattern.
Implementation & tests
Python tests: tests/test_dcg.py
sequence//1¶
DCG non-terminal that matches a list of terminals in sequence. sequence([a, b, c]) consumes a, b, c from the input. equivalent to inlining the terminals as a grammar rule body.
phrase(sequence(["hello", "world"]), ["hello", "world"]) % succeeds
phrase(sequence(["a", "b"]), ["a", "b", "c"], REST) % REST = ["c"]
Term Inspection¶
functor/3¶
Decompose a term into its functor name and arity, or construct a term from a name and arity (fields are fresh vars).
The Name position is an ATOM, in both directions — never a bare spelling, never a string:
| Call | Answer |
|---|---|
functor(foo(a), N, A) |
N = foo (an atom), A = 1 |
functor(bar, N, A) |
N = bar, A = 0 |
functor(42, N, A) |
N = 42, A = 0 |
functor([], N, A) |
N = [], A = 0 (as in Scryer) |
functor([1, 2], N, A) |
N = '.', A = 2 — a list is the '.'/2 structure |
functor("ab", N, A) |
N = '.', A = 2 — a string is the list of its chars |
functor("", N, A) |
N = [], A = 0 |
functor(T, foo, 2) |
T = foo(_, _) |
functor(T, foo, 0) |
T = foo |
functor(T, '.', 2) |
T = [_ \| _] — a partial LIST, never a '.'/2 cell |
functor(T, "foo", 1) |
type_error(atomic, "foo") — a string is a compound |
functor(T, 42, 2) |
type_error(atom, 42) |
The '.'/2 reading is a view: decomposition answers virtually (arg(2, "hello", T) gives the string "ello"), and construction through the name position builds the engine's real list shapes, never a (".", H, T) cell. See write_canonical/1 for the same view in the writer.
Implementation & tests
Seam tests: tests/fixtures/builtins_inspect.seam
Python tests: tests/test_builtins.py
arg/3¶
Unify arg with the N-th argument of Term (1-based indexing). N must
be bound: an unbound N is instantiation_error (ISO 8.5.2.3, as Scryer; it
used to enumerate the (N, arg) pairs, an SWI extension).
Implementation & tests
Seam tests: tests/fixtures/builtins_inspect.seam
Python tests: tests/test_builtins.py
unpack/2¶
unpack(+Term, -List) % decompose: List = [functor | Args]
unpack(-Term, +List) % construct: Term from [functor | Args]
[functor | args] list, or construct a term from such a list. (Prolog's =.. operator.) The head of the list is an ATOM, the same name position functor/3 uses:
| Call | Answer |
|---|---|
unpack(foo(a, "b"), L) |
L = [foo, a, "b"] |
unpack(bar, L) |
L = [bar] |
unpack(42, L) |
L = [42] |
unpack([1, 2], L) |
L = ['.', 1, [2]] |
unpack("abc", L) |
L = ['.', a, "bc"] |
unpack(T, [foo, 1]) |
T = foo(1), a cell |
unpack(T, ['.', a, "bc"]) |
T = "abc" — a char consed onto a string is a string |
unpack(T, ['.', 1, [2]]) |
T = [1, 2] — a Python list |
unpack(T, ["foo", 1]) |
type_error(atom, "foo") |
unpack(T, ["foo"]) |
type_error(atomic, "foo") |
Constructed compounds are cells (plain tuples) — Python code tests a constructed term's shape with clausal.cell_functor / clausal.cell_args.
Implementation & tests
Seam tests: tests/fixtures/builtins_inspect.seam
Python tests: tests/test_builtins.py
copy_term/2¶
Unify Copy with a deep copy of Original where every unbound Var is replaced by a fresh one. Structural sharing is preserved: if the same Var appears in multiple positions in Original, the same fresh Var appears in all corresponding positions of Copy. Already-bound variables are followed and their values are copied rather than replaced.
A cyclic term (X = f(X), which =/2 builds with no occurs check) is
copied as a cycle, and a term nested too deep for the recursive walker is
copied by an iterative one (clausal/logic/rational_walk.py); the same holds
for ground/1, term_variables/2 and the copies findall/3 makes.
Implementation & tests
Seam tests: tests/clausal_modules/term_inspection.seam
Python tests: tests/test_term_inspection.py
copy_term/3¶
Copy is a copy of Term whose variables carry no attributes, and Goals the list of goals that, called, put back on them the constraints the variables of Term carry: dif(X, a), copy_term(X, Y, Gs) gives Gs = [dif(Y,a)]. The goals are those the answer printers show (dif/2, CLP(ℤ), freeze/2, when/2, CLP(B), CLP(ℝ), CLP(Q)); see Coroutining. Scryer's and SWI's copy_term/3.
Implementation & tests
Implementation: clausal/logic/builtins/inspection.py, clausal/logic/residuals.py
Tests: tests/iso/test_copy_term_3_scryer.py, tests/fixtures/copy_term_3.clausal, tests/fixtures/copy_term_3.seam
term_variables/2¶
Unify Vars with a list of all unbound Vars in Term, collected left-to-right with duplicates removed (same Var appearing multiple times in Term appears only once in Vars). Bound variables are followed and not collected.
Implementation & tests
Seam tests: tests/clausal_modules/term_inspection.seam
Python tests: tests/test_term_inspection.py
numbervars/3¶
Number all unbound Vars in Term left-to-right, binding each to the term '$VAR'(N) where N starts at Start and increments. End is unified with the next unused number after all variables are numbered. Useful for pretty-printing terms with named variables. Start must be a bound integer.
Implementation & tests
Seam tests: tests/clausal_modules/term_inspection.seam
Python tests: tests/test_term_inspection.py
gensym/2¶
Generate a unique atom by appending a monotonically increasing counter to Prefix. gensym(x, A) produces the atoms x_1, x_2, etc. on successive calls. The counter is not trailed — it survives backtracking (impure, matches Prolog's gensym/2). Thread-safe via lock. Different prefixes maintain independent counters. Prefix must be a bound atom; anything else (unbound, a "..." string, a number) fails.
Implementation & tests
Implementation: clausal/logic/builtins/inspection.py (gensym/2)
Python tests: tests/test_term_inspection.py
global_atom/2¶
global_atom(+Name, -Atom) % mint-on-demand: returns (and creates if absent)
global_atom(+Name, +Atom) % guard: succeeds iff Atom is the global class for Name
global_atom(-Name, +Atom) % reverse lookup: succeeds iff Atom is genuinely global
global_atom(-Name, -Atom) % enumerate global atoms (ordering not guaranteed)
.clausal file an atom is written bare (foo) or quoted ('foo bar'), and global_atom(foo, A) answers A = foo. Name is an atom, read by its spelling; a bound Name that is not an atom (a string, a char list under -double_quotes(chars), a number) raises type_error(atom, Name) rather than failing. Four modes:
(+Name, -Atom)— mint on demand. LookName's spelling up in the global dict; if absent, installmint(spelling). Idempotent: a second call with the same spelling unifiesAtomwith the same atom. This is the sanctioned way to reach the global atom for a name from a module that has shadowed it via-import_fromor a local declaration — though a quoted literal ('date') already denotes the atom in any mode and needs no declaration.(+Name, +Atom)— guard. Succeeds iffAtomequals the atom registered underName's spelling (==, the correct test: two atoms of one spelling are one atom, the same internedstr— interning makesisagree too, but==is what to write).(-Name, +Atom)— reverse lookup. Succeeds iffAtomis genuinely the registered global atom for its spelling (not a module-local namesake). UnifiesNamewith that atom.(-Name, -Atom)— enumerate. Yields one solution per registered atom. The registry holds only atoms that reached it (through this builtin's mint mode, or a manual install), not every atom a program mentions; it can be empty. Ordering is not guaranteed.
To obtain an atom from text (a string or char list), use atom_chars/2 or atom_codes/2.
global_atom/2 is the reflection escape hatch for reaching a global atom by
name when a module-local declaration or an import shadows it — and the sanctioned
way for a strict-default file to obtain a global atom it does not list.
Implementation & tests
Implementation: clausal/logic/builtins/inspection.py (global_atom/2)
Python tests: tests/test_term_inspection.py (TestGlobalAtom)
constant_value/2¶
The constant Name names. Name is an atom; Value is its frozen ground value.
This is Markus Triska's name for the cross-implementation convention (2026-09-10), so the
spelling and arity are not Clausal Prolog's to vary: an exported .pl and any expansion prelude must
use exactly this.
:- module(m, [retry_limit/1]).
:- constant_value(max_retries, 3).
retry_limit(N) :-
constant_value(max_retries, N).
test("retry_limit") :-
retry_limit(N),
N == 3.
:- end_module(m).
(The seam declares it with -constant_value(max_retries, 3).)
Scope: program-wide, not module-implicit
In a Prolog system there is one program, so constant_value/2 is a fact about it. Clausal Prolog
has modules, and the module-implicit reading would need the calling module — which a
builtin does not get: the registry hands dispatch functions their arguments and a trail,
and nothing else. So this enumerates every loaded logic module's own declarations,
exactly as module_constant(-Module, +Name, ?Value) does. Two modules declaring the same
constant name both answer. Use module_constant/3 when the module
matters.
constant_number_units/3¶
Scope: the OWNING module, resolved at compile time (2026-09-12)
Unlike constant_value/2 above, this is module-scoped, and the
difference is worth understanding because the constraint they face is identical.
A builtin cannot receive the calling module. But the compiler knows it, so a written
constant_number_units(Name, N, U) is compiled to
module_constant_units/4 with the owning module inserted —
the same way $module is handed to the registration when a declaration is lowered.
Reading works the way writing already does.
The module inserted is the name's owner, which is not always the caller: an imported constant is registered on the module that declared it, so the compiler uses the module the import named.
Consequences, all of them intentional:
- a name this module neither declares nor imports cannot be written — it is a compile-time error naming the way out, rather than silently answering with some other module's declaration in load order;
- an imported constant answers here (it did not before);
- with the name unbound this enumerates, but only this module's own declarations.
constant_value/2 keeps the program-wide reading: its name and arity are fixed by
cross-implementation convention, so its scope is not ours to vary.
A constant declared with :- constant_number_units(Name, Number, Units). (the seam's -constant_number_units).
Name is an atom, Number the magnitude, Units the unit expression.
Named for what it can hold: only numbers carry units, which is why this is not
constant_value_units/3. The directive enforces it — a non-numeric value is a load-time
error naming the directive.
A constant declared without units has no solution here. It has a value but no units, and
constant_value/2 is the predicate that relates it; answering with a
dimensionless marker would make every constant look united.
It reports the DECLARATION, not the stored value
These differ whenever the declared unit is not the base of its own dimension, because the
units library rescales to that base. :- constant_number_units(standstill, 30, day). stores
Quantity(2592000, second) — both the 30 and the day are unrecoverable from the value.
constant_number_units(standstill, N, U) |
N = 30, U = day |
constant_value(standstill, V) |
V = 2592000 second |
The two disagree about the number on purpose: constant_value/2 is the value view,
and this one exists to report what the declaration said. That is what lets a check assert
a parameter's declared unit matches the unit its name claims — impossible against the
normalised pair, where every duration is second whatever was written.
Units is the unit expression as declared:
| declared | Units |
|---|---|
:- constant_number_units(max_fine, 5000, euro). |
euro |
:- constant_number_units(speed, 3, metre / second). |
metre / second |
:- constant_number_units(area, 7, metre ** 2). |
metre ** 2 |
:- module(m, [limit/2]).
:- use_module(european_union, [euro]).
:- constant_number_units(max_fine, 5000, euro).
limit(N, U) :-
constant_number_units(max_fine, N, U).
test("limit") :-
limit(N, U),
N == 5000,
U == euro.
:- end_module(m).
(The seam declares it with -constant_number_units(max_fine, 5000, euro).)
module_constant_units/4¶
The declared pair, scoped to one module — standing to
constant_number_units/3 exactly as
module_constant/3 stands to constant_value/2.
Module is a module object; Name is the constant's spelling. Reports the declaration,
not the stored value, for the reasons given at constant_number_units/3.
A module that does not declare Name simply fails. This is a lookup, not an assertion —
the error for a name nothing declares belongs at the constant_number_units/3 call site, where
the compiler can see the name was written as a literal and refuse it before anything runs.
This is also the relation constant_number_units/3 compiles to, with the owning module
inserted. Writing it by hand is for the case where the module you want is not the one you are
in and not one you imported the name from.
module_constant/3¶
module_constant(+Module, +Name, ?Value) % look up / check a declared constant
module_constant(+Module, -Name, ?Value) % enumerate Module's own constants
module_constant(-Module, +Name, ?Value) % find which loaded module(s) declare Name
module_constant(-Module, -Name, ?Value) % enumerate every loaded module's constants
:- constant_value(Name, Value). declarations (the seam's -constant_value),
naming the module explicitly. Module is the Python module object a seam
-import_module(...) directive binds — the same object a qualified constant reference like
other_module.pi resolves against. A .clausal file has no such binding, and an atom does not
name the module (module_constant(m, max_retries, V) fails), so from Clausal Prolog Module
is the object the (-Module, +Name, ?Value) mode answers; Name is the constant's declaration spelling as an atom
(max_retries); Value is the
constant's frozen value — the identical object the declaring module's own clause bodies embed.
The seam spelling (a .clausal file has no -import_module):
# m.seam
-module(m, [])
-constant_value(max_retries, 3)
# caller.seam
-import_module(m)
retry_limit(N) <- module_constant(m, max_retries, N)
Four modes, following directly from which of Module/Name are bound:
(+Module, +Name, ?Value)— look up / check. Fails ifModuledeclares no constant namedName; otherwise checks/bindsValue.(+Module, -Name, ?Value)— enumerate a module's constants. One solution per(Name, Value)pairModuledeclares.(-Module, +Name, ?Value)— find the declaring module(s). Searches every loaded logic module (a snapshot ofsys.modules) for one that declares a constant namedName;Moduleneed not be imported into the querying file.(-Module, -Name, ?Value)— enumerate everything. One solution per(Module, Name, Value)triple across every loaded logic module.
Only a module's own declarations are reflected — a constant reached via -import_from or
-import_module is not re-registered on the importer, so module_constant/3 never sees it
there. Query the module that actually declared it instead (see
Importing constants).
Implementation & tests
Implementation: clausal/logic/builtins/inspection.py (module_constant/3),
clausal/logic/constants.py (register_module_constant),
clausal/logic/database.py (Module.constants)
Python tests: tests/test_module_constant_reflection.py
Runtime Database¶
These work on a predicate declared :- dynamic(Name/Arity). (declare first). A static predicate raises error(permission_error(modify, static_procedure, Name/Arity), assertz/1) (or asserta/1, retract/1). A name with no declaration and no clauses follows the module flag assert_creates_dynamic: it is on in a .clausal module, so assertz/asserta create the name as dynamic (ISO 7.5.2(2)); a seam module has it off and refuses them. See Database operations.
assertz/1¶
Add the fact Clause at the end of its predicate's clause list. Only facts can be asserted: a rule raises permission_error(assert, rule, Head). A static predicate raises error(permission_error(modify, static_procedure, Name/Arity), assertz/1); a name nothing declares is created as dynamic in a .clausal module, and refused the same way in a seam module (static by default, ISO 7.5.2); an unbound Clause raises instantiation_error.
Implementation & tests
Seam tests: tests/fixtures/builtins_db.seam
Python tests: tests/test_builtins.py
asserta/1¶
Add Clause at the front of its predicate's clause list.
Implementation & tests
Seam tests: tests/fixtures/builtins_db.seam
Python tests: tests/test_builtins.py
retract/1¶
Remove the first clause whose head unifies with Term. Not backtrackable — removes exactly one clause per call. As in ISO (8.9.3) and Scryer: it fails when nothing matches, including for a name nothing declares (there is no clause to remove); a static predicate, a declared data functor or a builtin raises error(permission_error(modify, static_procedure, Name/Arity), retract/1); an unbound Term raises instantiation_error. (retractall/1 and abolish/1 are not provided.)
Implementation & tests
Seam tests: tests/fixtures/builtins_db.seam
Python tests: tests/test_builtins.py
clause/2¶
ISO 8.8.1: Body unifies with the body of each clause of a dynamic
predicate whose head unifies with Head (true for a fact), in the logical
update view. A static predicate raises
permission_error(access, private_procedure, Name/Arity), as does a builtin
or control construct; an unknown one fails.
:- dynamic(edge/2).
:- dynamic(path/2).
edge(1, 2).
path(X, Y) :-
edge(X, Y).
static_fact(1).
test("fact body is true") :-
clause(edge(1, _), true).
test("rule body is a term") :-
clause(path(A, B), BODY),
BODY == edge(A, B).
test("a static predicate is private") :-
catch(clause(static_fact(_), _), E, true),
E == error(permission_error(access, private_procedure, static_fact/1), clause/2).
Implementation & tests
Implementation: clausal/logic/builtins/clause_ops.py
Python tests: tests/test_clause_2_iso.py
abolish_table/2¶
Remove all cached answers for the named tabled predicate, forcing re-computation on the next call.
Implementation & tests
Seam tests: none
Python tests: tests/test_tabling.py
abolish_all_tables/0¶
Remove all cached tabling answers for every predicate in the current database.
Implementation & tests
Seam tests: none
Python tests: tests/test_tabling.py
Prolog Flags¶
The ISO flags and assert_creates_dynamic; the table of flags, values and
scopes is in Prolog Flags.
set_prolog_flag/2¶
Set a flag (ISO 8.17.1). A module-scoped flag (assert_creates_dynamic) is set
for the calling module; double_quotes is set only by a directive (the seam's
-set_prolog_flag). Errors are ISO's:
instantiation_error, type_error(atom, F), domain_error(prolog_flag, F),
domain_error(flag_value, F+V), and permission_error(modify, flag, F) for a
read-only flag or a value this engine does not implement.
Implementation & tests
Implementation: clausal/logic/builtins/flags.py
Python tests: tests/iso/test_prolog_flags_scryer.py
current_prolog_flag/2¶
The value of a flag (ISO 8.17.2); a module-scoped flag reports the calling
module's value. With Flag unbound it enumerates every flag that has a value
(max_integer and min_integer have none: integers are unbounded).
Implementation & tests
Implementation: clausal/logic/builtins/flags.py
Python tests: tests/iso/test_prolog_flags_scryer.py
char_conversion/2¶
Put the pair InChar -> OutChar in the character conversion table (ISO
8.14.5), or take InChar out of it when the two are the same character. The
table is process-wide; also a directive, :- char_conversion(a, b). Errors are
ISO's: instantiation_error for an unbound argument,
representation_error(character) for one that is not a one-char atom. No
reader applies the table: the char_conversion flag is off and cannot be set
on (Prolog Flags), so text is read as written. Refused in the
sandbox.
Implementation & tests
Implementation: clausal/logic/builtins/flags.py
Python tests: tests/iso/test_char_conversion_scryer.py
current_char_conversion/2¶
InChar is converted to the different character OutChar by the table (ISO
8.14.6); with InChar unbound it enumerates the table. An argument bound to
anything but a one-char atom is representation_error(character).
Implementation & tests
Implementation: clausal/logic/builtins/flags.py
Python tests: tests/iso/test_char_conversion_scryer.py
Operators¶
One process-wide operator table, as in ISO 8.14.3 and Scryer. op/3 run as
a goal changes it and current_op/3 reads it. Loading a .pl or .clausal
file adds to it what Scryer makes global: the :- op/3 directives of a file
that is not a module, and the ops a module exports in its module/2 list. A
module's own unexported :- op/3 governs only how that file is read. Every
file is read with its own fresh table, so op/3 run as a goal does not
change how loaded source reads.
op/3¶
Sets (priority 1..1200) or removes (priority 0) the operator(s) Operator,
an atom or a list of atoms, of Specifier's class (ISO 8.14.3). The ISO
8.14.3.3 errors include permission_error(modify, operator, ',') for any
op/3 on the comma, and permission_error(create, operator, Name) for [],
{}, a | that is not infix with priority 1001 or more, and a name that
would be both infix and postfix. The same checks refuse the :- op/3
directive at load. A refused op/3 changes nothing.
Implementation & tests
Implementation: clausal/logic/builtins/operators.py, clausal/tools/prolog_operators.py
Python tests: tests/iso/test_iso_op3_current_op3.py
current_op/3¶
Enumerates the operators in the table (ISO 8.14.4). A bound argument of the
wrong kind is domain_error(operator_priority, P),
domain_error(operator_specifier, S) or type_error(atom, O).
Implementation & tests
Implementation: clausal/logic/builtins/operators.py
Python tests: tests/iso/test_iso_op3_current_op3.py
Keyword-Term Introspection¶
These predicates address a term's fields by name; the names come from the functor's declaration, which only the seam can write (-private([point(x, y, z)])), so this section is about seam terms. See Term Inspection § Fields by name. The keyword construction spelling point(x=1), KWTerm and extend/3 are gone.
vary/3¶
Produce a copy of Term with field values replaced by Overrides (a Python dict). Works on declared functor cells.
Implementation & tests
Seam tests: tests/fixtures/builtins_keywords.seam
Python tests: tests/test_builtins.py
unbound_keys/2¶
Unify Keys with a list of field names whose values are unbound Vars in Term.
Implementation & tests
Seam tests: tests/fixtures/builtins_keywords.seam
Python tests: tests/test_builtins.py
signature/3¶
Reflect the registered parameter name list for the predicate FunctorName/Arity. Fails if no signature is registered.
Implementation & tests
Seam tests: tests/fixtures/builtins_keywords.seam
Python tests: tests/test_builtins.py
Attributed Variables¶
Attributed variables carry key-value metadata that survives through unification. This is the mechanism that powers CLP(ℤ), CLP(B), CLP(ℝ), dif/2, and units constraints internally. These predicates expose the API so users can build custom constraint solvers.
Attribute keys are atoms — put_attr(X, my_key, V), or 'my key' when the name needs quoting. A string key raises type_error(atom, Key). Attribute values can be any term. All mutations are trailed (undone on backtracking).
put_attr/3¶
Attach attribute Value under the atom Key to an unbound variable. Overwrites any existing value for that key. Trailed.
get_attr/3¶
Retrieve the attribute stored under Key. Fails if Var has no attribute for Key, or if Var is not an unbound variable.
del_attr/2¶
Remove the attribute under Key. Succeeds even if no attribute existed (no-op). Trailed.
get_attrs/2¶
Unify Attrs with a DictTerm containing all attributes on Var, keyed by the same atoms put_attr/3 takes. Empty DictTerm if no attributes.
put_attrs/2¶
Set multiple attributes from a DictTerm. Each key-value pair is applied via put_attr.
attvar/1¶
Succeeds if Var is an unbound variable with at least one attribute. Fails for bound terms and for bare (non-attributed) variables.
term_attvars/2¶
Collect all attributed variables occurring in Term into a list. Traverses compound terms, lists, DictTerms, and term instances recursively. Each variable appears at most once.
Constraint Predicates¶
dif/2¶
Disequality constraint. Succeeds if X and Y can remain different (posts a constraint if either is unbound). Implemented via attributed variables; propagates through unification.
Implementation & tests
Seam tests: tests/fixtures/builtins_dif.seam
Python tests: tests/test_dif.py
eq/3 (reified)¶
Reified equality. T is unified with true if X = Y, false if dif(X, Y). Suspends if neither is determined yet.
Implementation & tests
Seam tests: tests/fixtures/reif_eq_test.seam, tests/fixtures/builtins_dif.seam
Python tests: tests/test_reif_builtins.py
dif_t/3 (reified)¶
Reified disequality. T is true if dif(X, Y), false if X = Y.
Implementation & tests
Seam tests: tests/fixtures/builtins_dif.seam
Python tests: tests/test_reif_builtins.py
=/3 and dif/3 (library(reif))¶
Scryer's library(reif) names: =(X, Y, T) is eq/3 (T = true with
X = Y first, then T = false with dif(X, Y)), and dif(X, Y, T) is its
negation in the SAME answer order (T = false first; dif_t/3 answers
true first). A .clausal or .pl file's if_(X = Y, ...) and closures such as
tfilter(=(a), ...) run on them, and so does the seam's
if_('='(X, Y), ...). if_/3's library(reif) meaning is described in
Reified if-then-else.
#=(X, Y, T) and #<(X, Y, T) are clpz's reified comparisons (Scryer's
clpz_t/2: X #= Y #<==> B, then T = false for B = 0 and T = true
for B = 1, in that order), so if_(X #= 3, ...) takes a CLP(ℤ) condition.
Implementation & tests
Python tests: tests/iso_l3/test_l3_s4_constructs.py, tests/iso_l3/test_l3_if_runtime_reif.py
CLP(ℤ) — Integer Constraints¶
CLP(ℤ) operates over all integers — variables default to the entire integer line (-∞, +∞) until constrained. The comparison operators of library(clpz) (#=, #\=, #<, #=<, #>, #>=; the seam spells them ==, !=, <, <=, >, >=) map to _fd_eq, _fd_ne, _fd_lt, _fd_le, _fd_gt, _fd_ge. The predicates below are the builtin-registry interface.
in_domain/3¶
Post the integer domain [Lo, Hi] on a logic variable or a list of logic variables. Required before label/1 can enumerate values.
Implementation & tests
Seam tests: tests/fixtures/clpfd_queens.seam, tests/fixtures/clpfd_sendmore.seam
Python tests: tests/test_clpfd.py
label/1¶
Enumerate concrete values for a list of constrained variables, backtracking over all consistent assignments. Variables must have finite domains (via in_domain/3 or comparison constraints) — raises ValueError on unbounded domains.
Implementation & tests
Seam tests: tests/fixtures/clpfd_queens.seam, tests/fixtures/clpfd_sendmore.seam
Python tests: tests/test_clpfd.py
all_different/1¶
Post an all-different constraint on a list of integer-constrained variables. Propagates bounds and eliminates assigned values from other domains.
Implementation & tests
Seam tests: tests/fixtures/clpfd_queens.seam, tests/fixtures/clpfd_sendmore.seam
Python tests: tests/test_clpfd.py
structural_eq/2¶
True structural equality (ISO ==/2: T1 == T2; the seam writes it quoted, '=='(T1, T2)). Succeeds if T1 and T2 are identical after dereferencing variables, without binding any variables and without evaluating arithmetic. Recursively walks compound terms (cells), lists, SegLists, DictTerms, and user-defined term dataclasses.
For structural inequality use T1 \== T2.
Implementation & tests
Implementation: clausal/logic/builtins/constraints.py → clausal/logic/constraints.py:structural_eq
Tests: tests/conformity/test_iso_unification.py:TestStructuralEquality
Python tests: tests/test_clpfd.py
sum_/3¶
Constrain the sum of Vars (a list of FD variables or integers) under comparison operator Op to Value. Supported operators: #=, #<, #>, #=<, #>=, #\=.
For #=, posts a SumConstraint that propagates bounds in both directions: narrows Value to [min_sum, max_sum] and narrows each variable using the remaining slack. For inequality operators, an intermediate variable is introduced and chained with the appropriate binary relational constraint. Ground lists with a ground Value are checked immediately without posting a constraint.
scalar_product/4¶
Weighted sum constraint: Σ(Coeffs[i] * Vars[i]) Op Value. Coefficients must be ground integers. Lists must be the same length. Supports negative coefficients — division direction is flipped accordingly when narrowing individual variables.
Uses the same bounds-consistency approach as sum_/3 (ScalarProductConstraint). For inequality operators, an intermediate variable is introduced and chained with a binary relational constraint.
element/3¶
Value is the Index-th element of List (1-based indexing). when Index is ground, performs direct lookup. when Index is an FD variable, posts an ElementConstraint that propagates bidirectionally: narrows Index to positions whose list element overlaps Value's domain, and narrows Value to the union of the domains at valid positions. Then enumerates the surviving valid indices.
element(2, [10, 20, 30], V) % V = 20
element(I, [10, 20, 30], 20) % I = 2 (propagated without labeling)
circuit/1¶
Constrain Vars to form a single Hamiltonian circuit. Vars[i] = j means the successor of node i+1 is node j (1-based). Posts a CircuitConstraint that: restricts all domains to [1, n], removes self-loop values, enforces all_different, and detects premature sub-tours via forced-chain analysis — pruning values that would close a cycle shorter than n. Labeling then enumerates remaining candidates.
circuit([2, 3, 1]) % valid: 1→2→3→1
% circuit([1, 2, 3]) fails — self-loop at node 1
% circuit([2, 1, 4, 3]) fails — two sub-tours (detected during propagation)
CLP(B) — Boolean Constraints¶
CLP(B) uses reduced ordered BDDs (Binary Decision Diagrams) for Boolean constraint solving. Expressions use Python's bitwise operators: & (AND), | (OR), ^ (XOR), ~ (NOT), plus BoolEq (equivalence) and BoolImpl (implication) term constructors. The operators are seam syntax: from a .clausal file only variables, 0, 1, 'BoolEq'(X, Y) and 'BoolImpl'(X, Y) are accepted (see CLP(B)).
sat/1¶
Post a Boolean constraint. The expression must evaluate to true. Fails if unsatisfiable. Propagates forced values (e.g., sat(X & Y) forces both to 1).
Implementation & tests
Implementation: clausal/logic/builtins/constraints.py → clausal/logic/clpb.py
Seam tests: tests/fixtures/clpb_circuit.seam
Python tests: tests/test_clpb.py
taut/2¶
Tautology check. Unify T with 1 if Expr is always true, 0 if always false. Fail if indeterminate.
Implementation & tests
Implementation: clausal/logic/builtins/constraints.py → clausal/logic/clpb.py
Seam tests: none
Python tests: tests/test_clpb.py
sat_count/2¶
Count the number of satisfying assignments for Expr. Unify N with the count.
Implementation & tests
Implementation: clausal/logic/builtins/constraints.py → clausal/logic/clpb.py
Seam tests: none
Python tests: tests/test_clpb.py
bool_labeling/1¶
Enumerate 0/1 assignments for a list of Boolean variables. Backtracks over all satisfying assignments.
Implementation & tests
Implementation: clausal/logic/builtins/constraints.py → clausal/logic/clpb.py
Seam tests: tests/fixtures/clpb_circuit.seam
Python tests: tests/test_clpb.py
Type Checks¶
var/1¶
Succeeds if X is an unbound logic variable.
Implementation & tests
Seam tests: tests/fixtures/builtins_types.seam
Python tests: tests/test_builtins.py
nonvar/1¶
Succeeds if X is bound (not an unbound Var).
Implementation & tests
Seam tests: tests/fixtures/builtins_types.seam
Python tests: tests/test_builtins.py
atom/1¶
Succeeds if X is an atom: the interned Python str itself. Written bare
(red) or single-quoted ('hello world'). (In the seam a bare atom is
declared, via -private([red, blue]), -module(m, [red]) or an import; a
quoted one needs no declaration.) A string is not an atom — use string/1 / is_str/1 for that —
and neither is []. From Python, build one with
clausal.logic.atoms.mint("red") and read its spelling with spelling/1.
is_str/1 and string/1¶
Succeeds if X is a string — the term a "…" literal denotes, which is the list of its character atoms. Does not match atoms (a bare str is an atom, not a string) — use atom/1 for those — and note that atomic/1 rejects a string, because a string is a list. See Type Checking for the full table.
Implementation & tests
Implementation: clausal/logic/builtins/type_checks.py
Python tests: tests/test_builtins.py
atomic/1¶
Succeeds if X is an atomic constant: an atom, a number, a bool, or another indivisible value. It is false for a string, which is a list, and false for a compound term.
Implementation & tests
Implementation: clausal/logic/builtins/type_checks.py
Python tests: tests/test_builtins.py
Implementation & tests
Seam tests: tests/fixtures/builtins_types.seam
Python tests: tests/test_builtins.py
number/1¶
Succeeds if X is an int or float (excludes bool).
Implementation & tests
Seam tests: tests/fixtures/builtins_types.seam
Python tests: tests/test_builtins.py
integer/1¶
Succeeds if X is an int (excludes bool).
Implementation & tests
Seam tests: tests/fixtures/builtins_types.seam
Python tests: tests/test_builtins.py
float_/1¶
Succeeds if X is a Python float.
Implementation & tests
Seam tests: tests/fixtures/builtins_types.seam
Python tests: tests/test_builtins.py
compound/1¶
Succeeds if X is a compound term with arity > 0: a cell ('f', …), or a non-empty list or string (the '.'/2 structure, as in ISO). An atom is arity 0, so compound/1 rejects it, and so is [] (= "").
Implementation & tests
Seam tests: tests/fixtures/builtins_types.seam
Python tests: tests/test_builtins.py
callable_/1¶
Succeeds if X is an atom or a compound term — something that could appear as a goal. As in ISO, a non-empty string is a '.'/2 compound and so is callable: call("foo") raises existence_error(procedure, '.'/2), not a type error.
Implementation & tests
Seam tests: tests/fixtures/builtins_types.seam
Python tests: tests/test_builtins.py
is_list/1¶
Succeeds if X is list-shaped: a Python list, or a string, which is the list of its character atoms. Use is_str/1 when you need to tell a character sequence (string) apart from a plain list — a bare atom (str) satisfies neither.
Implementation & tests
Seam tests: tests/fixtures/builtins_types.seam
Python tests: tests/test_builtins.py
ground/1¶
Succeeds if X contains no unbound Vars (is fully instantiated).
Implementation & tests
Seam tests: tests/fixtures/builtins_types.seam
Python tests: tests/test_builtins.py
must_be/2¶
Assert that Term is of the given type. Succeeds silently if it matches. Throws instantiation_error if Term is unbound, and error(type_error(Type, Term), must_be/2) if Term is ground but of the wrong type.
The Type argument is an atom. Supported types: integer, float, number, atom, atomic, string / str, list, character, chars, boolean, callable, dict, compound. character is a one-character atom and chars a list of them, as Scryer's library(error): must_be(chars, [a|_]) and must_be(chars, [a,_]) raise instantiation_error, must_be(chars, [a,1|_]) raises type_error(character, 1) and must_be(chars, [a|b]) raises type_error(list, [a|b]) -- those two type errors with the context can_be/2, as Scryer's. atom and string are separate types: must_be(atom, "abc") raises, and so does must_be(string, abc).
In the seam, quote a type name that is also a builtin
In a .clausal file must_be(integer, 3) is fine. In the seam, integer, float, number, atom, callable and compound are also builtin predicate names, and a bare builtin name in an argument is the builtin's object, not the atom: must_be(integer, 3) raises type_error(atom, <builtin integer/1>). Write must_be('integer', 3) there.
can_be/2¶
Assert that Term could possibly be of the given type. Succeeds if Term is unbound (it could become anything) or already matches the type. Throws type_error only when Term is ground and definitely the wrong type. The Type argument is an atom, and the same types must_be/2 takes.
Dict and Set Predicates¶
Dict and set builtins operate on DictTerm/SetTerm values and equally on plain Python dict/set — the plain flavor is accepted wherever the Term flavor is (they unify and compare equal; outputs bind the Term flavor). The dict and set literals ({"a": 1}, {1, 2}) are seam syntax; a .clausal file builds them with dict_pairs/2 and set_list/2 (dict_pairs(D, [a-1, b-2]) gives D = {a:1,b:2}), and {a:1} written in a .clausal file is the ISO curly term, not a dict. See Dicts and Sets for the full design, including the always-available Python dict surface: P[key] subscript, get/3, get/4, tri_get/3, key in P, {**P, k: v} splat-merge, and delete/3.
Implementation & tests
Implementation: clausal/logic/builtins/dict_set.py
Python tests: tests/test_dict_set_builtins.py (79 tests)
Fixture: tests/fixtures/dict_set_builtins.seam
get/3, get/4, get_strict/3, tri_get/3, delete/3 — the dict surface¶
The DICT-first read/removal family mirroring Python's dict.get/del:
get(Dict, Key, Value) soft-fails on an absent key, get(Dict, Key, Value,
Default) binds the default, tri_get(Dict, Key, Value) binds Undefined
(and, unlike get/3,4, throws type_error(dict, Dict) on a non-dict),
and delete(Dict, Key, NewDict) removes functionally (throws on absent).
The strict read is the subscript, V is Dict[Key], and its predicate form
get_strict(Dict, Key, Value) (same argument order as get/3), which throws
existence_error(dict_key, Key) on an absent key with the subscript's other
errors too — the one strict read ISO syntax (.pl) can spell. From .seam
it is an ordinary call, get_strict(D, 'k', V); from .clausal, get_strict(D, k, V). Documented in full at
The Python dict surface.
is_dict/1¶
Succeeds if Term is a DictTerm or a plain dict.
is_dict_t/2 (reified)¶
Reified is_dict/1, in the manner of dif_t/3: T is true if Term is a
dict (whatever is_dict/1 accepts), false for any other nonvar term — one
answer, no choice point. An unbound Term is an instantiation_error. A
bound T makes it a test; a T that is neither true nor false fails, as
it does for dif_t/3. It is a closure for library(reif)'s if_/3:
if_(is_dict_t(P), Then, Else). See
Dicts and sets.
Implementation & tests
Python tests: tests/test_is_dict_t.py, tests/iso_l3/test_l3_is_dict_t.py
dict_size/2¶
N is the number of keys in Dict.
dict_keys/2¶
Keys is the list of keys in the standard order of terms (ISO 7.2), as msort/2.
dict_values/2¶
Values is the list of values, ordered by their keys in the standard order of terms (ISO 7.2).
dict_pairs/2¶
Bidirectional: Dict ↔ list of Key-Value pairs (the '-'(Key, Value) cell, as pairs_keys_values/3). In dict→pairs direction, pairs are ordered by key in the standard order of terms (ISO 7.2).
dict_get/3¶
Semidet lookup. Fails if Key is absent or unbound.
dict_put/4¶
Functional update: NewDict is OldDict with Key → Value set. Returns a new DictTerm.
dict_put_pairs/3¶
Bulk update from a list of Key-Value pairs, equivalent to repeated dict_put/4.
dict_remove/3¶
NewDict is OldDict without Key. Fails if Key is absent.
dict_merge/3¶
union of D1 and D2. Where keys conflict, D2's value wins.
gen_dict/3¶
Nondeterministic enumeration. Yields one Key/Value binding per solution on backtracking. Can be filtered by binding Key before the call.
sub_dict/2¶
Partial dict matching. Succeeds when every key in Pattern is present in Dict and the values unify. Extra keys in Dict are ignored. See sub_dict for examples.
is_set/1¶
Succeeds if Term is a SetTerm.
set_size/2¶
N is the cardinality of Set.
set_list/2¶
Bidirectional: Set ↔ sorted list. In list→set direction, duplicates are removed. Ordered by the standard order of terms (ISO 7.2: variables, then every float, then every other number by value, then atoms, then compound terms), as msort/2.
set_union/3¶
Set union.
set_intersection/3¶
Set intersection.
set_subtract/3¶
Diff = elements in S1 not in S2.
set_sym_diff/3¶
Symmetric difference: elements in exactly one of S1, S2.
set_subset/2¶
Succeeds if Sub is a subset of Super (including equal sets and the empty set).
set_disjoint/2¶
Succeeds if S1 and S2 share no elements.
set_add/3¶
NewSet is OldSet with Elem added. No-op if already present.
set_remove/3¶
NewSet is OldSet with Elem removed. No-op if absent.
gen_set/2¶
Nondeterministic enumeration of set elements, in the standard order of terms (ISO 7.2), as msort/2.
Arithmetic¶
Arithmetic posts CLP(ℤ) constraints with library(clpz)'s #= (e.g., Y #= X * 2; the seam spells it Y == X * 2), or evaluates with ISO is/2. The predicates below provide relational arithmetic usable in both input and output modes.
between/3¶
Check or enumerate integers in [Low, High] inclusive. In check mode (X bound) succeeds iff Low ≤ X ≤ High. In generate mode (X unbound) backtracks over each integer.
Both bounds must be integers. High cannot be the atom inf or infinite, which SWI-Prolog accepts: between(1, inf, X) raises type_error(integer, inf), as in Scryer and Trealla. For an unbounded count, use length(_, N) or repeat/0 with a counter.
Implementation & tests
Seam tests: tests/fixtures/builtins_arith.seam
Python tests: tests/test_builtins.py, tests/test_search.py, tests/iso/test_repeat_between_bounds_scryer.py
succ/2¶
Bidirectional successor: if X is bound, Y = X + 1; if Y is bound, X = Y - 1. Both must be non-negative integers.
Implementation & tests
Seam tests: tests/fixtures/builtins_arith.seam
Python tests: tests/test_builtins.py
plus/3¶
Relational addition: any two of X, Y, Z determine the third.
Implementation & tests
Seam tests: tests/fixtures/builtins_arith.seam
Python tests: tests/test_builtins.py
abs_/2¶
Absolute value.
Implementation & tests
Seam tests: tests/fixtures/builtins_arith.seam
Python tests: tests/test_builtins.py
max_/3¶
Implementation & tests
Seam tests: tests/fixtures/builtins_arith.seam
Python tests: tests/test_builtins.py
min_/3¶
Implementation & tests
Seam tests: tests/fixtures/builtins_arith.seam
Python tests: tests/test_builtins.py
sign/2¶
sign of X. Returns -1 for negative, 0 for zero, 1 for positive. Supports Quantity values (result is always a dimensionless integer).
gcd/3¶
Greatest common divisor of two integers. Supports Quantity values — dimensions must agree; result preserves dimensions.
divmod_/4¶
Integer division and modulus. Fails if Y is 0. Supports Quantity values — dimensions must agree; quotient Q is dimensionless, remainder R preserves dimensions.
lcm/3¶
Least common multiple of two integers. Supports Quantity values — dimensions must agree; result preserves dimensions.
exp_mod/4¶
Modular exponentiation using Python's efficient pow(base, exp, mod). Integer-only (no Quantity support). Fails if Mod is 0.
popcount/2¶
Population count (number of 1 bits). X must be a non-negative integer.
msb/2¶
Most significant bit position. X must be a positive integer. msb(8, B) gives B=3.
lsb/2¶
Least significant bit position. X must be a positive integer. lsb(12, B) gives B=2.
Quantity support in arithmetic
plus, abs_, max_, min_, sign, gcd, divmod_, and lcm all accept
Quantity values (numbers with physical dimensions). Dimension mismatches
raise UnitsMismatch — they are not silenced. exp_mod, popcount, msb,
and lsb are integer-only (bitwise operations have no dimensional
interpretation).
List Predicates¶
Strings accepted
All list predicates accept strings as character lists. append("hel", "lo", X) yields X = "hello". when all inputs are strings and the result is a character sequence, the result is returned as a string. See Strings as Lists.
in_/2¶
Enumerate or check membership. Backtracks over all elements.
Implementation & tests
Seam tests: tests/fixtures/meta_test.seam, tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py, tests/test_search.py
in_check/2¶
Deterministic membership check. Succeeds at most once; no backtracking.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
append/3¶
List concatenation. Works in all modes: given any two, determines the third. Backtracks over splits when L3 is bound and L1/L2 are unbound.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py, tests/test_search.py
length/2¶
List length in both directions.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
last/2¶
Unify Elem with the last element of List.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py, tests/test_search.py
reverse/2¶
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py, tests/test_search.py
list_item/3¶
Get the element at 0-based index N.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
flatten/2¶
Recursively flatten a nested list structure.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
msort/2¶
sort List preserving duplicate elements (stable sort). Ordered by the standard order of terms (ISO 7.2: variables, then every float, then every other number by value, then atoms, then compound terms).
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
sort/2¶
sort List removing duplicate elements. Ordered by the standard order of terms (ISO 7.2: variables, then every float, then every other number by value, then atoms, then compound terms), as msort/2.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
sort/4¶
SWI-Prolog's sort/4 (Scryer has none). Key is 0 (the whole element), N (its N-th argument), an atom (a dict's value for that key) or a list of these (a path: [1, 2] is argument 2 of argument 1). Order is @< (ascending, duplicate keys removed), @=< (ascending, all kept), @> or @>= (descending); the bare <, =<, >, >= are accepted too. The sort is stable, and where duplicates are removed the first is kept: sort(1, @<, [f(2,a), f(1,b), f(2,c)], S) gives S = [f(1,b), f(2,a)]. sort(0, @<, L, S) is sort/2, sort(0, @=<, L, S) msort/2, sort(1, @=<, Pairs, S) keysort/2. Errors as SWI's, checked Key, then Order, then List: an unbound one or a partial list is an instantiation error; domain_error(not_less_than_one, K) for a negative key, type_error(sort_key, K) for another non-key, type_error(atom, O) / domain_error(order, O), type_error(list, L), and for an element without the key type_error(compound, E) or existence_error(argument, N, E).
Implementation & tests
Implementation: clausal/logic/builtins/lists.py (_sort__4)
Python tests: tests/iso/test_common_extras_scryer.py
permutation/2¶
Enumerate all permutations of List via backtracking.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py, tests/test_search.py
select/3¶
select Elem from List, unifying Rest with the remaining elements. Backtracks over all positions where Elem appears.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
subtract/3¶
List difference: elements in Set1 not in Set2.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
intersection/3¶
Elements present in both Set1 and Set2.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
union/3¶
Elements in Set1 or Set2, with duplicates removed.
Comparison in subtract/3, intersection/3 and union/3
These three compare elements with ==/2, so they never bind a
variable. SWI-Prolog and Trealla compare with memberchk/2, which
unifies, so an unbound element can give a different answer:
| Goal | Clausal | Trealla/SWI |
|---|---|---|
subtract([X],[a],R) |
R=[X] |
X=a, R=[] |
intersection([X],[a],R) |
R=[] |
X=a, R=[a] |
union([X],[a],R) |
R=[X,a] |
X=a, R=[a] |
Scryer's library(lists) has none of the three.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
list_to_set/2¶
Remove duplicates from List preserving the first-occurrence order.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
sum_list/2¶
sum_ all numeric elements of List.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
max_list/2¶
Maximum element of a non-empty numeric list. Numeric order: elements compare by value, as arithmetic comparison does (1 < 2.0), not by the standard order of terms.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
min_list/2¶
Minimum element of a non-empty numeric list. Numeric order: elements compare by value, as arithmetic comparison does (1 < 2.0), not by the standard order of terms.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
take/3¶
First N elements of List. If N > len(List), returns the whole list. If N = 0, returns [].
Implementation & tests
Implementation: clausal/logic/builtins/lists.py (_take__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
drop/3¶
List after dropping the first N elements. If N >= len(List), returns [].
Implementation & tests
Implementation: clausal/logic/builtins/lists.py (_drop__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
split_at/4¶
Split List at index N into Left (first N elements) and Right (rest). Clamps to list bounds.
Implementation & tests
Implementation: clausal/logic/builtins/lists.py (_split_at__4)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
zip_/3¶
Pair up elements from two lists into X-Y pairs (the '-'(X, Y) cell). Truncates to the shorter list.
Implementation & tests
Implementation: clausal/logic/builtins/lists.py (_zip__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
replicate/3¶
List of N copies of Elem.
Implementation & tests
Implementation: clausal/logic/builtins/lists.py (_replicate__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
split_with/3¶
Split List by separator Sep into sublists (Parts). In join mode, interleaves Parts with Sep.
Implementation & tests
Implementation: clausal/logic/builtins/lists.py (_split_with__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
pairs_keys_values/3¶
Relate a list of Key-Value pairs to separate Keys and Values lists, as in Scryer's library(pairs). Works in every direction; a pair it builds is the cell '-'(K, V). A non-list, or an element that is not a pair, fails (no error). See Pairs.
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
pairs_keys/2¶
The keys of a list of Key-Value pairs: pairs_keys_values(Pairs, Keys, _).
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
pairs_values/2¶
The values of a list of Key-Value pairs: pairs_keys_values(Pairs, _, Values).
Implementation & tests
Seam tests: tests/fixtures/builtins_lists.seam
Python tests: tests/test_builtins.py
group_pairs_by_key/2¶
Group adjacent Key-Value pairs whose keys are identical (==), as in Scryer's library(pairs). Groups is a list of Key-Values. It does not sort: sort the pairs first (msort/2) to collect every occurrence of a key into one group.
group_pairs_by_key([a-1, a-3, b-2], GROUPS)
% GROUPS = [a-[1, 3], b-[2]] (adjacent pairs only: [a-1, b-2, a-3] gives three groups)
map_list_to_pairs/3¶
Pairs is [K1-E1, K2-E2, ...] with call(Goal, Ei, Ki) for each element of List, as in Scryer's library(pairs). Every solution of each call is an answer on backtracking. See Pairs.
Implementation & tests
Implementation: clausal/logic/builtins/higher_order.py (_map_list_to_pairs__3)
Python tests: tests/test_map_list_to_pairs.py
numlist/3¶
List is the list of integers from Low to High inclusive. Fails if Low > High.
numlist/2¶
Shorthand for numlist(1, High, List).
same_length/2¶
Succeeds if L1 and L2 have the same length. If one is ground and the other is unbound, generates a list of fresh variables with matching length.
transpose/2¶
Column-wise transposition of a list of lists. All rows must be the same length (fails on non-rectangular input). Empty matrix transposes to empty list.
Higher-Order List Predicates¶
These predicates accept a goal argument (a lambda or named predicate). The goal is called for each list element; failures propagate as in standard higher-order patterns.
maplist/2¶
Verify that Goal(Elem) succeeds for every element of List. Fails if any element fails.
Implementation & tests
Seam tests: tests/fixtures/builtins_higher_order.seam
Python tests: tests/test_higher_order.py
maplist/3¶
Map Goal(X, Y) over Xs to produce Ys. Takes the first solution of Goal per element.
Implementation & tests
Seam tests: tests/fixtures/builtins_higher_order.seam
Python tests: tests/test_higher_order.py
maplist/4 .. maplist/9¶
maplist(Goal, L1, ..., Ln) calls Goal(E1, ..., En) on the elements of
the lists in step (Scryer's library(lists)); lists of different lengths give
no answer, an open list is enumerated as by maplist/2,3, and every
solution of every call is an answer on backtracking. maplist/9 runs on
call/9.
Implementation & tests
Python tests: tests/iso_l3/test_l3_s4_constructs.py
include/3¶
include List keeping only elements for which Goal(Elem) succeeds.
Implementation & tests
Seam tests: tests/fixtures/builtins_higher_order.seam
Python tests: tests/test_higher_order.py
exclude/3¶
include List keeping only elements for which Goal(Elem) fails.
Implementation & tests
Seam tests: tests/fixtures/builtins_higher_order.seam
Python tests: tests/test_higher_order.py
partition/4¶
Split List into two: Included contains elements where Goal(Elem) succeeds, Excluded contains elements where it fails.
tfilter/3¶
Reified filter. Calls Goal(Elem, T) where T is a fresh variable bound to true or false by the goal. Keeps elements where T = true. Committed choice: only the first solution of Goal is used.
Useful with reified predicates like eq/3 and dif_t/3 that always succeed but bind their truth-value argument.
tpartition/4¶
Reified partition. Calls Goal(Elem, T) for each element. Elements where T = true go into Included, T = false into Excluded.
foldl/4¶
Left fold. Calls Goal(Elem, Acc0, Acc1) for each element, threading the accumulator. V0 is the initial value; V is the final result. foldl/5 and foldl/6 fold over two and three lists (Goal(X, Y, Acc0, Acc1), ...), as Scryer's library(lists). Every solution of each call is an answer on backtracking, and an open list enumerates (see Higher-Order).
Implementation & tests
Seam tests: tests/fixtures/builtins_higher_order.seam
Python tests: tests/test_higher_order.py
take_while/3¶
Longest prefix of List where Goal(Elem) succeeds for each element.
Implementation & tests
Implementation: clausal/logic/builtins/higher_order.py (_take_while__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
drop_while/3¶
Suffix of List after dropping the longest prefix where Goal(Elem) succeeds.
Implementation & tests
Implementation: clausal/logic/builtins/higher_order.py (_drop_while__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
span/4¶
take_while + drop_while in one pass. Yes is the longest prefix where Goal succeeds; No is the rest.
Implementation & tests
Implementation: clausal/logic/builtins/higher_order.py (_span__4)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
group_by/3¶
Group consecutive elements by key projected via Goal(Elem, Key). Elements with equal consecutive keys are collected into sublists.
Implementation & tests
Implementation: clausal/logic/builtins/higher_order.py (_group_by__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
sort_by/3¶
sort List by key projected via Goal(Elem, Key). Stable sort (preserves order of equal keys). Keys are compared in the standard order of terms (ISO 7.2: variables, then every float, then every other number by value, then atoms, then compound terms), as msort/2 compares them.
Implementation & tests
Implementation: clausal/logic/builtins/higher_order.py (_sort_by__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
predsort/3¶
SWI-Prolog's predsort/3: sort List as sort/2 does, but order two elements by calling call(Pred, Delta, E1, E2), which binds Delta to <, > or =; on = the second element is dropped, so elements Pred calls equal collapse to one. With compare it is sort/2. The comparisons are SWI's merge sort's, in its order. Every answer of Pred is tried, as maplist/2 tries every answer of its goal, so the predicate is cut-free (SWI commits to the first answer of each merge comparison; for a comparator with one answer per pair, such as compare/3, the two agree); an answer whose Delta is something else is no answer. A partial List is an instantiation error, a non-list type_error(list, L).
Implementation & tests
Implementation: clausal/logic/builtins/higher_order.py (_predsort__3)
Python tests: tests/iso/test_common_extras_scryer.py
max_by/3¶
element of List with the largest key projected via Goal(Elem, Key). Fails on empty list. Keys are compared in the standard order of terms (ISO 7.2), as msort/2: max_by of keys 1 and 2.0 is the element keyed 1; for the largest number use max_list/2.
Implementation & tests
Implementation: clausal/logic/builtins/higher_order.py (_max_by__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
min_by/3¶
element of List with the smallest key projected via Goal(Elem, Key). Fails on empty list. Keys are compared in the standard order of terms (ISO 7.2), as msort/2; for the smallest number use min_list/2.
Implementation & tests
Implementation: clausal/logic/builtins/higher_order.py (_min_by__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
filter_map/3¶
Map + filter in one pass. Calls Goal(Elem, Out) for each element; keeps Out when the goal succeeds, skips the element when it fails.
Implementation & tests
Implementation: clausal/logic/builtins/higher_order.py (_filter_map__3)
Seam tests: tests/fixtures/list_util.seam
Python tests: tests/test_list_util.py
Character/String¶
Logic-aware character and atom predicates that participate in unification and backtracking. Unlike Python string methods, these are relations — e.g. atom_concat(A, B, hello) with A and B unbound enumerates all splits, char_type(C, digit) enumerates digits.
These take ATOMS, not strings
Every predicate in this section whose ISO name begins atom_ (plus char_code/2, char_type/2, upcase_atom/2, downcase_atom/2) takes an atom in the atom position and answers with atoms. Handing one a string raises type_error(atom, S) — atom_length("abc", N) is an error, not a failure. char_code/2 raises type_error(character, S) for the same reason.
That is the ISO/Scryer split: an atom is a symbol, a string is the list of its character atoms, and the two never unify. See Atoms vs strings.
Prefer list predicates for STRING operations
A string is a list, so append/3 subsumes atom_concat/3, length/2 subsumes atom_length/2, list_item/3 indexes, in_/2 tests membership, and reverse/2 reverses. Reach for the atom_* family when you are working with an atom, or when you need it as the bridge between the two kinds: atom_chars/2 turns an atom into the char list of its spelling and back. See Strings as Lists.
% ATOM in, ATOMS out:
atom_length(hello, 5)
atom_concat(he, llo, hello)
upcase_atom(hello, 'HELLO')
char_code(a, 97)
char_type(a, alpha)
% atom_chars/2 is the bridge: an atom's spelling AS a char list, which is
% the same term as the string of that text.
atom_chars(hello, "hello")
atom_chars(A, "hello") % A = hello, an atom
% A STRING in an atom position is an ERROR, not a failure:
% atom_length("hello", N) --> type_error(atom, "hello")
% char_code("a", C) --> type_error(character, "a")
% For a STRING, use the list predicates -- a string IS a list:
length("hello", 5)
append("he", "llo", "hello")
char_type/2¶
Character classification as a relation. Char is a char atom ('a'), Type an atom. At least one argument must be bound. Types: alpha, digit, alnum, space, upper, lower, ascii, punct, print, control. With Char bound, enumerates matching types. With Type bound, enumerates matching ASCII characters. With both bound, tests membership.
Implementation & tests
Implementation: clausal/logic/builtins/chars.py
Python tests: tests/test_chars.py
char_code/2¶
Bidirectional char-atom ↔ integer code point conversion. char_code('A', N) unifies N with 65. char_code(C, 65) unifies C with the atom 'A'. Both bound tests equality. Both unbound raises instantiation_error. A string in the Char position raises type_error(character, S) — "a" is the one-element list ['a'], not the character.
Implementation & tests
Implementation: clausal/logic/builtins/chars.py
Python tests: tests/test_chars.py
upcase_atom/2¶
Unify Upper with the uppercase version of Atom — atom in, atom out. The first argument must be a bound atom; a string raises type_error(atom, …).
downcase_atom/2¶
Unify Lower with the lowercase version of Atom — atom in, atom out. The first argument must be a bound atom; a string raises type_error(atom, …).
atom_length/2¶
Unify length with the number of characters in Atom's spelling. The first argument must be a bound atom; atom_length("abc", N) raises type_error(atom, "abc") — use length/2, which counts a string's characters because a string is a list.
atom_chars/2¶
Bidirectional conversion between an atom and the list of its character atoms — the bridge between atoms and text. atom_chars(hi, L) unifies L with ['h', 'i'], which is the same term as the string "hi". atom_chars(A, ['h', 'i']) and atom_chars(A, "hi") both unify A with the atom hi. A string in the first position raises type_error(atom, "hi"); a non-list in the second — an atom included — raises type_error(list, hi).
atom_codes/2¶
Bidirectional conversion between an atom and the list of its integer code points. atom_codes(hi, L) unifies L with [104, 105].
atom_concat/3¶
Atom concatenation as a relation. Forward: A and B bound → unify C with the atom of their concatenated spellings. Reverse: C bound, A and/or B unbound → enumerate all splits as atoms. atom_concat(A, B, abc) yields 4 solutions: ('', abc), (a, bc), (ab, c), (abc, ''). Optimized paths for prefix/suffix-bound cases. To concatenate strings, use append/3.
Implementation & tests
Implementation: clausal/logic/builtins/chars.py
Python tests: tests/test_chars.py
sub_atom/5¶
Sub-atom relation. Relates an atom to the atoms of its sub-spellings with position information: Before + length + After = len(Atom), Sub = Atom[Before:Before+length], and every Sub answer is an atom. Multi-modal — any combination of bound/unbound arguments works (Atom must be bound). With Sub bound, uses str.find() for efficient lookup. Otherwise enumerates all valid (Before, length) pairs. For substrings of a string, use append/3 or the multi-star patterns of Strings as Lists.
Implementation & tests
Implementation: clausal/logic/builtins/chars.py
Python tests: tests/test_chars.py
number_chars/2¶
Bidirectional number ↔ character-list conversion. Number bound → Chars unifies with the list of the number's character atoms (which is the same term as the string of its digits). Chars a ground list (a char list or the string that is that list) → read as a number token (below) and unified with Number, whether or not Number is bound. Both unbound → instantiation error. Rejects bool values (not considered numbers).
A ground Chars is READ as a Prolog number token, as ISO 8.16.7 and Scryer read it: layout and comments may lead (" 1" is 1), a - may stand before the token, and 0x1A, 0'a, 1_000, 1_ 000 (layout may follow a digit group _, as in Scryer; operator ruling 2026-11-03) and 1.5e-3 are numbers; nothing may follow the token ("1 ", "+1", "1e5", "inf" are not numbers). Text that is not a number raises Scryer's syntax_error(unexpected_end_of_file) (the text ended before a number was read) or syntax_error(unexpected_char) (context number_chars/2:0). With both arguments bound the text is read, so number_chars(1, ['0', '1']) holds. -0.0 reads as 0.0, as the reader and Scryer read it (operator ruling 2026-10-24). number_codes/2 shares this behaviour. (Until 2026-09-30 the text was parsed with Python's int()/float() and a non-number FAILED.)
A ground Chars is READ as a Prolog number token, as ISO 8.16.7 and Scryer read it: layout and comments may lead (" 1" is 1), a - may stand before the token, and 0x1A, 0'a, 1_000, 1_ 000 (layout may follow a digit group _, as in Scryer; operator ruling 2026-11-03) and 1.5e-3 are numbers; nothing may follow the token ("1 ", "+1", "1e5", "inf" are not numbers). Text that is not a number raises Scryer's syntax_error(unexpected_end_of_file) (the text ended before a number was read) or syntax_error(unexpected_char), with the context every syntax error has, context(number_chars/2, [line(L), column(C), found(F)]): where the text ended, or the character that may not be there (operator ruling 2026-10-24; see Exceptions). With both arguments bound the text is read, so number_chars(1, ['0', '1']) holds. number_codes/2 shares this behaviour. (Until 2026-09-30 the text was parsed with Python's int()/float() and a non-number FAILED.)
number_chars(42, ['4', '2']) % succeeds -- the elements are char ATOMS
number_chars(-3.14, CHARS) % CHARS = ['-', '3', '.', '1', '4'] (printed "-3.14")
number_chars(N, ['1', '0']) % N = 10
number_chars(N, "10") % N = 10 -- same term as ['1', '0']
Implementation & tests
Implementation: clausal/logic/builtins/chars.py
Python tests: tests/test_chars.py
number_codes/2¶
Bidirectional number ↔ code-point-list conversion. Like number_chars/2 but uses integer code points (ord/chr) instead of character atoms.
number_codes(42, [52, 50]) % succeeds (char_code('4', 52), char_code('2', 50))
number_codes(N, [52, 50]) % N = 42
Implementation & tests
Implementation: clausal/logic/builtins/chars.py
Python tests: tests/test_chars.py
atom_string/2¶
SWI-Prolog's atom_string/2: String is the string of Atom's text, or Atom the atom of String's. Either side may be any text: an atom, a number, a string, or a list of characters or codes (atom_string(A, 42) gives A = '42'). A string is the chars carrier, so atom_string(abc, S) gives S = "abc", the list [a,b,c]. With both bound the texts are compared (atom_string(1, "1") holds). Neither side text: type_error(string, S) for a bound String, else type_error(atom, A) for a bound Atom, else an instantiation error.
Implementation & tests
Implementation: clausal/logic/builtins/chars.py (_atom_string__2)
Python tests: tests/iso/test_common_extras_scryer.py
I/O¶
write/1¶
Print Term to stdout without a trailing newline, unquoted — ISO 8.14.2's write_term(Term, [numbervars(true)]). An atom prints its spelling bare; a STRING prints as the list of characters it is, so write("abc") prints [a,b,c] and write([a, b]) prints [a,b]; a b"…" code list prints as its code numbers (write(b"ab") → [97,98]). List syntax is kept (f(a,b), [1,2]), with no space after a comma — the ISO family's output is byte-comparable with other ISO systems. Logic variables are auto-dereferenced — bound vars print their value, unbound vars print _N.
For human text — and for the seam's f-strings — use write_text/1 / writeln_text/1, which print a string as its characters. Use print_term/1 when you need to tell an atom from a string.
Implementation & tests
Python tests: tests/test_io.py
writeq/1¶
Print Term to stdout quoted, without a trailing newline — ISO 8.14.2's write_term(Term, [quoted(true), numbervars(true)]). An atom is quoted when its spelling is not a bare token ('foo bar'); a STRING is the list of its characters, as in write/1, so writeq("abc") prints [a,b,c] and writeq(f(a, "b")) prints f(a,[b]). List syntax is kept, unlike write_canonical/1, and so is the ISO comma spacing — none.
print_term/1 and term_to_string/2 are the Clausal Prolog display form — write_term(Term, [quoted(true), double_quotes(true)]) — which prints "abc"; reach for those when you need to tell an atom from a string at a glance.
Implementation & tests
Implementation: clausal/logic/builtins/io.py (writeq/1)
Python tests: tests/test_writers_atoms_strings.py
print/1¶
SWI-Prolog's print/1: write_term(Term, [portray(true), numbervars(true), quoted(true)]). There is no portray/1 hook, so it prints exactly what writeq/1 prints, with no newline.
Implementation & tests
Implementation: clausal/logic/builtins/io.py (_print__1)
Python tests: tests/iso/test_common_extras_scryer.py
write_term/2¶
Print Term to stdout under an ISO write-option list (ISO 8.14.2), without a trailing newline. Both Boolean options default to false, so write_term(Term, []) is the strict ISO display.
| Option | Effect |
|---|---|
quoted(Bool) |
quote an atom that would not read back as itself ('foo bar') |
double_quotes(Bool) |
print a string — and the char list that is one — as "abc" rather than [a,b,c] |
ignore_ops(Bool) |
true writes every compound in canonical form, ignoring the operator table: write_term(1+2, [ignore_ops(true)]) prints +(1,2) |
numbervars(Bool) |
true writes '$VAR'(N) as a variable name ('$VAR'(1) prints B); false writes the term itself |
variable_names(List) |
ISO 7.10 / WG17 N246: a variable identical to V in a Name = V pair of List prints as Name, unquoted, instead of _N; when several pairs name one variable the first in list order wins. An unbound List (or an unbound element, Name or tail) raises instantiation_error; a malformed element, a non-atom Name or an improper tail raises domain_error(write_option, variable_names(List)) |
| Call | Output |
|---|---|
write_term("abc", []) |
[a,b,c] |
write_term("abc", [quoted(true)]) |
[a,b,c] |
write_term("abc", [quoted(true), double_quotes(true)]) |
"abc" |
write_term([a, b], []) |
[a,b] |
write_term('a b', [quoted(true)]) |
'a b' |
write_term(Term, []) is exactly write/1 and write_term(Term, [quoted(true)]) is exactly writeq/1. write_term(Term, [quoted(true), double_quotes(true)]) gives a string the spelling print_term/1 and term_to_string/2 give it; those two additionally keep the display comma spacing, which this writer, being ISO, does not. An unrecognised option raises domain_error(write_option, Opt); a non-list Options raises type_error(list, Options); an unbound or partial Options ([quoted(true) | _]) raises instantiation_error. write_term/3 takes the output stream first (see ISO streams); max_depth(N) is not supported.
Implementation & tests
Implementation: clausal/logic/builtins/io.py (write_term/2)
Python tests: tests/test_writers_atoms_strings.py
write_canonical/1¶
Print Term to stdout quoted, ignoring operator syntax and list syntax: every list — a string included — prints as the '.'/2 cons structure it denotes, with no space after commas, so the output is byte-comparable with other ISO systems.
| Term | write_canonical output |
|---|---|
"hello" |
'.'(h,'.'(e,'.'(l,'.'(l,'.'(o,[]))))) |
[1, 2] |
'.'(1,'.'(2,[])) |
[] |
[] |
foo(a, "b") |
foo(a,'.'(b,[])) |
1 + 2 |
+(1,2) |
The cons form is a view, not the representation: a string stays a compact str and a list stays a Python list. The same view is what functor/3 and =.. report for them.
Implementation & tests
Implementation: clausal/logic/builtins/io.py (write_canonical/1)
Python tests: tests/test_writers_atoms_strings.py
writeln/1¶
Like write/1 (ISO, unquoted) but appends a newline. Not an ISO name; writeln_text/1 is the text form.
Implementation & tests
Python tests: tests/test_io.py
write_text/1¶
Print Term to stdout as text, without a trailing newline. A STRING prints as its characters and a char list as the text it spells (write_text("abc") → abc, write_text([a, b]) → ab); an atom prints its bare spelling; every other term prints exactly as write/1 prints it. "" / [] print [].
This is Clausal Prolog's ~s, and in the seam it is where f-strings go: write_text(f"X is {X}"). write/1 is the ISO writer and spells a string out as [a,b,c].
Implementation & tests
Implementation: clausal/logic/builtins/io.py (write_text/1)
Python tests: tests/test_io.py
writeln_text/1¶
Like write_text/1 but appends a newline. In the seam, writeln_text(f"X is {X}") is the idiomatic way to print an interpolated line.
Implementation & tests
Implementation: clausal/logic/builtins/io.py (writeln_text/1)
Python tests: tests/test_io.py
print_term/1¶
Print the Clausal Prolog display representation of Term — an atom quoted where it needs it, a string in double quotes (the spelling write_term(Term, [quoted(true), double_quotes(true)]) gives), compounds as functor/args, and the display ", " after a comma that the ISO family drops — followed by a newline. Useful for debugging, because it distinguishes an atom from a string.
Implementation & tests
Python tests: tests/test_io.py
nl/0¶
Print a newline to stdout.
Implementation & tests
Python tests: tests/test_io.py
tab/1¶
Print N spaces to stdout. N must be a bound non-negative integer.
Implementation & tests
Python tests: tests/test_io.py
write_to_string/2¶
Unify String with the ISO (write/1) rendering of Term, as a string — a string spells itself out as [a,b,c]. Does not print anything. write_text_to_string/2 is the text form.
Implementation & tests
Python tests: tests/test_io.py
write_text_to_string/2¶
Unify String with the text (write_text/1) rendering of Term, as a string — a string passes through as its characters. Does not print anything. This is the one to build human-readable text with.
Implementation & tests
Implementation: clausal/logic/builtins/io.py (write_text_to_string/2)
Python tests: tests/test_io.py
term_to_string/2¶
Unify String with the Clausal Prolog display rendering of Term, as a string — the write_term(Term, [quoted(true), double_quotes(true)]) spelling plus the display ", " after a comma. Does not print anything.
Implementation & tests
Python tests: tests/test_io.py
term_to_atom/2¶
SWI-Prolog's term_to_atom/2. With Atom unbound, Atom is Term written with write_term(Term, [quoted(true)]): term_to_atom(f(X, 'A'), A) gives A = 'f(_123,\'A\')'. With Atom bound to text (an atom, a number, a string, a char or code list), the text is read as one term and unified with Term: the native ISO reader, the operators in force, the module's double_quotes flag, the end . optional. A bound Atom that is not text raises type_error(string, A); text that does not read as one term raises a syntax_error with the reader's kind and context, error(syntax_error(Kind), context(term_to_atom/2, [line(L), column(C), expected(What), found(Token)])) (layout only: syntax_error(end_of_string); a second term: syntax_error(end_of_clause_expected), located where it starts).
Implementation & tests
Implementation: clausal/logic/builtins/io.py (read_term_from_text)
Python tests: tests/iso/test_common_extras_scryer.py
atom_to_term/3¶
SWI-Prolog's atom_to_term/3: Atom's text read as term_to_atom/2 reads it, and Bindings the list of Name = Var for its named variables in order of first occurrence (read_term/2's variable_names; _ is left out): atom_to_term('foo(X, Y, X)', T, B) gives T = foo(_A, _B, _A), B = ['X' = _A, 'Y' = _B]. An unbound Atom is an instantiation error, a non-text one type_error(string, A), and a Bindings that is not a list type_error(list, B).
Implementation & tests
Implementation: clausal/logic/builtins/io.py (read_term_from_text)
Python tests: tests/iso/test_common_extras_scryer.py
listing/1¶
Print all clauses of a predicate to stdout: a .pl / Clausal Prolog predicate exactly as Scryer's listing/1 prints it (portray_clause/1 layout, variables A, B, ..., no header), a seam predicate in seam syntax (head <- body.) after a clause-count header. Follows Scryer Prolog's contract (operator ruling 2026-09-25): the argument is a predicate indicator, Name/Arity or Name//Arity (the latter names Name/(Arity+2)); an unbound argument, or an indicator naming no predicate or one with no clauses, FAILS; any other term (a bare atom, a compound, a string, a number) raises type_error(predicate_indicator, PI); a malformed operand raises functor/3's error (instantiation_error, type_error(integer, A), domain_error(not_less_than_zero, A), type_error(atomic, N) for a string name, type_error(atom, N) for a number name). A user-written foo/2 / foo // 2 compiles to a runtime Div / FloorDiv node (/ and // are arithmetic operators); the cells ('/', Name, Arity) / ('//', Name, Arity) are also accepted. An indicator naming an IMPORTED predicate resolves to the exporter's predicate, so listing(qq/1) from a module that -import_froms qq prints what the exporter's listing(qq/1) prints. From Python it also takes a predicate HANDLE (each arity it is defined at is listed) or a builtin predicate ("% name/arity — builtin").
Implementation & tests
Implementation: clausal/logic/builtins/io.py (listing/1)
Python tests: tests/test_listing.py
portray_clause/1¶
Pretty-print a term with indentation for multi-line display using term_pformat. Short terms appear on one line; deeply nested terms are expanded with depth indentation.
Implementation & tests
Implementation: clausal/logic/builtins/io.py (portray_clause/1)
Python tests: tests/test_listing.py
ISO streams: open/4, close/2, stream_property/2 and the stream forms¶
open(+SourceSink, +Mode, -Stream) open(+SourceSink, +Mode, -Stream, +Options)
close(+Stream) close(+Stream, +Options)
current_input(?Stream) current_output(?Stream)
set_input(+Stream) set_output(+Stream)
flush_output flush_output(+Stream)
at_end_of_stream at_end_of_stream(+Stream)
set_stream_position(+Stream, +Position) stream_property(?Stream, ?Property)
get_char(?Char) get_char(+Stream, ?Char) peek_char(?Char) peek_char(+Stream, ?Char)
get_code(?Code) get_code(+Stream, ?Code) peek_code(?Code) peek_code(+Stream, ?Code)
put_char(+Char) put_char(+Stream, +Char) put_code(+Code) put_code(+Stream, +Code)
get_byte(?Byte) get_byte(+Stream, ?Byte) peek_byte(?Byte) peek_byte(+Stream, ?Byte)
put_byte(+Byte) put_byte(+Stream, +Byte) nl(+Stream) tab(+Stream, +N)
write(+Stream, +Term) writeq(+Stream, +Term) write_canonical(+Stream, +Term)
write_term(+Stream, +Term, +Options) format(+Stream, +Format, +Args)
'$stream'(N); a stream may also be named by an alias atom. user_input, user_output and user_error are predefined and stand for the Python process's sys.stdin, sys.stdout and sys.stderr at each use (a captured or replaced sys.stdout is honoured), so write/1 and the other one-argument writers write to the current output, by default user_output, exactly as before; set_output/1 redirects them and closing the current output stream makes user_output current again (likewise set_input/1, user_input).
open(F, Mode, S, Options) opens the file named by the atom F in mode read, write or append, UTF-8 for text. Options: type(text) (default) or type(binary); alias(A); eof_action(error | eof_code | reset) (default eof_code: reading past the end keeps answering end_of_file/-1; error raises permission_error(input, past_end_of_stream, S); reset tries the file again, for one that grows); reposition(Bool) (default: true for a seekable file not opened for append). Positions are opaque terms from stream_property(S, position(P)); set_stream_position(S, P) needs reposition(true) (else permission_error(reposition, stream, S)). stream_property/2 enumerates file_name(F), mode(M), input, output, alias(A), position(P), end_of_stream(not | at | past), eof_action(A), reposition(B) and type(T); user_input has mode(read), eof_action(reset); user_output and user_error have mode(append) (ISO 7.10.2.11).
SourceSink may also be a string or a list of characters or codes naming the file (as Scryer accepts), so open("data.txt", read, S) works in a .clausal file, whose double_quotes is chars. An OS failure of a stream operation after the open -- a full disk, a file closed underneath the stream, a sys.stdin that is None -- is error(system_error(io), PI). The current input and output are process-global (not per thread), and only the engine's writers go through them: the toplevel's and -g's answer printer, error messages and the seam's ++print(...) write to the Python streams directly, not through set_output/1.
get_char/2 answers a one-char atom or end_of_file; get_code/2 a code or -1; get_byte/2 a byte or -1 (binary streams only); the peek_ forms leave the item in the stream. Closing a standard stream has no effect; closing any other invalidates its term and aliases (existence_error(stream, S) afterwards). The error terms are ISO's: an unbound stream is instantiation_error; neither an atom nor a stream term domain_error(stream_or_alias, S) (current_input/1, current_output/1 and stream_property/2 take no alias in that position and say domain_error(stream, S)); an unknown alias or a closed stream existence_error(stream, S); the wrong direction permission_error(input | output, stream, S); the wrong kind permission_error(input | output, binary_stream | text_stream, S); open/4's domain_error(source_sink, F), domain_error(io_mode, M), domain_error(stream_option, O), uninstantiation_error(S), existence_error(source_sink, F) and permission_error(open, source_sink, F | alias(A) | reposition(true)); close/2's domain_error(close_option, O); the character arguments' type_error(in_character, C), type_error(character, C), type_error(integer, C), representation_error(in_character_code | character_code), type_error(in_byte, B), type_error(byte, B). In the sandbox every one of these is refused like the writers (see sandbox).
Implementation & tests
Implementation: clausal/logic/streams.py (the table), clausal/logic/builtins/streams_io.py, the stream forms in clausal/logic/builtins/io.py
Python tests: tests/test_streams.py; against Scryer row by row: tests/iso/test_streams_scryer.py
read/1,2, read_term/2,3¶
ISO 8.14.1 term input (since 2026-10-24). Reads one term -- up to and including its end token . -- from a text input stream (the current input for the short forms) with the native ISO reader and unifies it with Term; the layout character after the end token stays in the stream. The term is read with the run-time operator table (op/3 as a goal and a file's global op/3 directives count; an :- op(...) read as data changes nothing) and "..." under the reading module's double_quotes flag (chars, codes or atom). The result is an ordinary term: read(T), T = foo(X) works, [a,b|T] reads as a partial list.
Options: variables(Vs) (every variable, anonymous ones included, in first-occurrence order), variable_names(Ps) (Name = Var for each named variable, _X included, _ not), singletons(Ps) (the named variables occurring once). At the end of the stream Term is end_of_file and the three lists are []. A term that does not read is error(syntax_error(Why), read_term/3) and the stream is left after that item's end token, so the next read goes on with the next term; text without an end token at the end of the stream is a syntax error too, then end_of_file. An unbound or partial option list, or an unbound element, is instantiation_error; a non-list type_error(list, L); anything else domain_error(read_option, O). The stream errors are the stream predicates' (above); a binary stream is permission_error(input, binary_stream, S). The non-ISO syntax_errors/1 option is not provided.
Implementation & tests
Implementation: clausal/logic/builtins/read_term.py
Python tests: tests/test_read_term.py; against Scryer: tests/iso/test_read_term_scryer.py
Logging (log module)¶
Standard library module wrapping Python's logging. Import via :- use_module(library(logging), [...]) (the seam: -import_from(log, [...])). See logging.md for full documentation.
All logging predicates always succeed (side-effect only). Messages below the logger's configured level are silently discarded.
get_logger/1, get_logger/2¶
Unify Logger with a Python logging.Logger instance. Arity-1 returns the default "clausal" logger. Same name always returns same logger instance.
Implementation & tests
Implementation: clausal/modules/py/logging.py
Python tests: tests/test_logging_module.py
debug/1, debug/2¶
log at DEBUG level. Arity-1 uses default "clausal" logger.
Implementation & tests
Implementation: clausal/modules/py/logging.py
info/1, info/2¶
log at INFO level.
Implementation & tests
Implementation: clausal/modules/py/logging.py
warning/1, warning/2¶
log at WARNING level.
Implementation & tests
Implementation: clausal/modules/py/logging.py
error/1, error/2¶
log at ERROR level.
Implementation & tests
Implementation: clausal/modules/py/logging.py
critical/1, critical/2¶
log at CRITICAL level.
Implementation & tests
Implementation: clausal/modules/py/logging.py
log/3¶
log at an arbitrary level. Level is a string ("debug", "info", etc.) or integer.
Implementation & tests
Implementation: clausal/modules/py/logging.py
set_level/2¶
Set the logger's effective level.
Implementation & tests
Implementation: clausal/modules/py/logging.py
get_level/2¶
Unify Level with the logger's effective level name as a lowercase atom (e.g. debug); a bound Level may be the atom or text, in either case.
Implementation & tests
Implementation: clausal/modules/py/logging.py
is_enabled_for/2¶
Succeeds if the logger would process a message at Level; fails otherwise. The only logging predicate that can fail.
Implementation & tests
Implementation: clausal/modules/py/logging.py
stream_handler/2¶
Create a logging.StreamHandler. StreamName is "stdout" or "stderr".
Implementation & tests
Implementation: clausal/modules/py/logging.py
file_handler/2¶
Create a logging.FileHandler for the given path.
Implementation & tests
Implementation: clausal/modules/py/logging.py
set_formatter/2¶
Set a logging.Formatter on the handler using Python format string syntax.
Implementation & tests
Implementation: clausal/modules/py/logging.py
add_handler/2¶
Add a handler to the logger.
Implementation & tests
Implementation: clausal/modules/py/logging.py
remove_handler/2¶
Remove a handler from the logger.
Implementation & tests
Implementation: clausal/modules/py/logging.py
basic_config/1¶
Call logging.basicConfig() with a dict of options (level, format, datefmt, filename, filemode, stream).
Implementation & tests
Implementation: clausal/modules/py/logging.py
Date & Time (date_time module)¶
Standard library module wrapping Python's datetime. Import via :- use_module(library(datetime), [now/1, today/1, ...]) (the seam: -import_from(date_time, [now, today, date, ...])). The predicates compute with Python's datetime objects but take and give back terms — date(2026, 3, 16), time(14, 30, 0, 0), datetime(2026, 3, 16, 14, 30, 0, 0), timedelta(7, 0, 0); see Date & Time. In the seam, a datetime method can also be called via ++() interop.
now/1¶
Unify DT with datetime.datetime.now() (naive, local time).
Implementation & tests
Implementation: clausal/modules/py/datetime.py
Python tests: tests/test_date_time.py
now_utc/1¶
Unify DT with datetime.datetime.now(datetime.timezone.utc) (timezone-aware).
Implementation & tests
Implementation: clausal/modules/py/datetime.py
today/1¶
Unify D with datetime.date.today().
Implementation & tests
Implementation: clausal/modules/py/datetime.py
date/4¶
There is no date/4 predicate: library(datetime) does not export one, and calling it is existence_error(procedure, date/4). A date is the term date(Year, Month, Day), built and taken apart by unification; the predicates that read one raise domain_error(date, D) for an impossible date (Feb 29 in a non-leap year, month 13). See Date & Time.
Implementation & tests
Implementation: clausal/modules/py/datetime.py
Python tests: tests/test_date_time.py
time/4¶
Bidirectional. If TimeObj is unbound, constructs datetime.time(Hour, Minute, Second). If TimeObj is a datetime.time, decomposes into Hour, Minute, Second.
Implementation & tests
Implementation: clausal/modules/py/datetime.py
datetime/7¶
Bidirectional. If DtObj is unbound, constructs datetime.datetime(Year, Month, Day, Hour, Minute, Second). If DtObj is a datetime.datetime, decomposes into all six components.
Implementation & tests
Implementation: clausal/modules/py/datetime.py
timedelta/3¶
Bidirectional. If TdObj is unbound, constructs datetime.timedelta(days=Days, seconds=Seconds). If TdObj is a datetime.timedelta, decomposes into Days and Seconds.
Implementation & tests
Implementation: clausal/modules/py/datetime.py
date_add/3¶
Result = DateOrDatetime + Timedelta. Both inputs must be ground.
Implementation & tests
Implementation: clausal/modules/py/datetime.py
date_sub/3¶
Result = DateOrDatetime - Timedelta. Both inputs must be ground.
Implementation & tests
Implementation: clausal/modules/py/datetime.py
date_diff/3¶
Timedelta = D1 - D2. Both inputs must be datetime.date or datetime.datetime. Result is a datetime.timedelta (may be negative).
Implementation & tests
Implementation: clausal/modules/py/datetime.py
datetime_string/3¶
Bidirectional. Format mode (DateTime has strftime): String = DateTime.strftime(Format). Parse mode (DateTime unbound, String a string): DateTime = datetime.strptime(String, Format). Format must be a ground string. Note: strptime always yields a datetime, so a date round-trips to a midnight datetime.
Implementation & tests
Implementation: clausal/modules/py/datetime.py
weekday/2¶
Weekday = DateOrDatetime.weekday(). Monday = 0, Sunday = 6.
Implementation & tests
Implementation: clausal/modules/py/datetime.py
date_between/3¶
Nondeterministic — generates one solution for each datetime.date in [Start, End] (inclusive). Fails if Start > End. This is the only date_time predicate that backtracks.
Implementation & tests
Implementation: clausal/modules/py/datetime.py
Python tests: tests/test_date_time.py
timestamp/2¶
Bidirectional. Forward (DateTime is a datetime.datetime): Stamp = DateTime.timestamp() (float epoch seconds); with Stamp already bound this acts as a check. Inverse (DateTime unbound, Stamp a number): DateTime = datetime.fromtimestamp(Stamp). A plain date has no timestamp() — the forward direction requires a datetime.
Implementation & tests
Implementation: clausal/modules/py/datetime.py
Python tests: tests/test_date_time.py
datetime_string_iso/2, date_string_iso/2¶
datetime_string_iso(DT, S) % S = "2026-03-16T14:30:00" / inverse parses it
date_string_iso(D, S) % S = "2026-03-16" / inverse parses it
datetime_string_iso/2 forward requires a datetime.datetime and produces the full ISO-8601 string via isoformat(); inverse parses via fromisoformat. date_string_iso/2 forward requires a plain datetime.date (a datetime is rejected); inverse parses via date.fromisoformat. Both predicates catch (TypeError, ValueError) and fail cleanly; both-unbound fails.
Implementation & tests
Implementation: clausal/modules/py/datetime.py
Python tests: tests/test_date_time.py
ISO comparison and term order (quoted forms)¶
ISO's comparison and term-order predicates are builtins under their ISO
names. In a .clausal file the operators mean what ISO says, written bare
(A == B, X is E, A < B) or quoted ('=='(A, B)). In the seam a bare
== or < is a constraint (see below), so there they are written
quoted. They follow ISO 13211-1, and Scryer where ISO is silent:
| Builtin | Meaning |
|---|---|
'='(A, B), '\\='(A, B) |
unification; not unifiable |
'=='(A, B), '\\=='(A, B) |
identical / not identical in the standard order of terms |
'@<', '@>', '@=<', '@>=' (arity 2) |
standard order of terms |
compare(Order, A, B) |
Order is '<', '=' or '>' |
'=..'(Term, List) |
univ; the same relation as unpack/2 |
'is'(X, Expr) |
ISO is/2: evaluates Expr |
'=:=', '=\\=', '<', '>', '=<', '>=' (arity 2) |
ISO arithmetic comparison, both sides evaluated |
'#=', '#\\=', '#<', '#>', '#=<', '#>=' (arity 2) |
CLP(ℤ) constraints under clpz's names |
test("ISO forms, bare") :-
1 \== 2,
1 @< a,
compare(O, 1, 2),
O == (<),
X is 7 // 2,
X == 3,
1 =:= 1.0.
test("ISO forms, quoted") :-
'\\=='(1, 2),
'@<'(1, a),
'is'(X, 7 // 2),
'=='(X, 3),
'=:='(1, 1.0).
Which operator meaning applies to which spelling in the seam (bare = Python, quoted = Scryer) is set out in Operators; the evaluable functors are in Arithmetic.
Operator Syntax (Compiler Special Forms)¶
These bare spellings are the seam's syntax, compiled directly rather than
looked up as builtins. Operators is the reference for their
meaning. A .clausal file reads the same characters as ISO Prolog does; the
right-hand column is what it writes for the same meaning.
| Seam syntax | Meaning | Clausal Prolog |
|---|---|---|
X is Y |
unification, no evaluation (X is 1 + 2 binds X to the term 1 + 2; for ISO is/2 write 'is'(X, E) or eval_(E, X)) |
X = Y (and X is E evaluates) |
X is not Y |
disequality constraint (dif/2) |
dif(X, Y) |
X == Y, X != Y |
arithmetic equality / disequality constraint (clpz's #= / #\\=) |
X #= Y, X #\= Y |
X < Y, X <= Y, X > Y, X >= Y |
arithmetic ordering constraints | X #< Y, X #=< Y, X #> Y, X #>= Y |
X in Coll |
membership: enumerates the elements of Coll |
in_(X, Coll) |
X not in Coll |
negated membership check | none: refused from 2.0 (maplist(dif(X), Coll) is the monotone form) |
not Goal |
negation as failure | none: \+ Goal is refused from 2.0 (ISO \+ in a .pl module) |
Test Fixtures Summary
| Fixture | Predicates under test |
|---|---|
tests/fixtures/edge_graph.seam |
user-defined edge/2, reach/2 |
tests/fixtures/fibonacci.seam |
user-defined fib/2 |
tests/fixtures/dynamic_pred.seam |
-dynamic directive, color/2 |
tests/fixtures/static_pred.seam |
-discontiguous directive |
tests/fixtures/tabled_fib.seam |
-table directive, tabled fib/2 |
tests/fixtures/tabled_path.seam |
tabled path/2, cyclic graph |
tests/fixtures/tabled_mutual_rec.seam |
tabled mutual recursion |
tests/fixtures/tabled_left_rec.seam |
tabled left recursion |
tests/fixtures/tabled_same_gen.seam |
tabled same-generation |
tests/fixtures/tabled_ite.seam |
tabled predicate under not (was an if_/3 condition) |
tests/fixtures/clpfd_queens.seam |
in_domain/3, all_different/1, label/1 |
tests/fixtures/clpfd_sendmore.seam |
in_domain/3, all_different/1, label/1 |
tests/fixtures/wfs_win.seam |
well-founded semantics, not on tabled |
tests/fixtures/wfs_win_asym.seam |
well-founded semantics, asymmetric |
tests/fixtures/reified_memberd.seam |
if_/3, dif/2 (reified ITE) |
tests/fixtures/reified_max.seam |
if_/3 with arithmetic |
tests/fixtures/reif_eq_test.seam |
eq/3 |
tests/fixtures/once_member.seam |
once/1 |
tests/fixtures/meta_test.seam |
findall/3, setof/3, forall/2, in_/2 |
tests/fixtures/builtins_inspect.seam |
functor/3, arg/3, unpack/2 |
tests/clausal_modules/term_inspection.seam |
copy_term/2, term_variables/2, numbervars/3 |
tests/fixtures/builtins_db.seam |
assertz/1, asserta/1, retract/1 |
tests/fixtures/builtins_types.seam |
var/1, nonvar/1, is_str/1, number/1, integer/1, float_/1, compound/1, callable_/1, is_list/1, ground/1 |
tests/fixtures/builtins_arith.seam |
between/3, succ/2, plus/3, abs_/2, max_/3, min_/3 |
tests/fixtures/builtins_lists.seam |
in_/2, in_check/2, append/3, length/2, last/2, reverse/2, list_item/3, flatten/2, msort/2, sort/2, permutation/2, select/3, subtract/3, intersection/3, union/3, list_to_set/2, sum_list/2, max_list/2, min_list/2, pairs_keys_values/3, pairs_keys/2, pairs_values/2 |
tests/fixtures/builtins_higher_order.seam |
maplist/2, maplist/3, include/3, exclude/3, foldl/4 |
tests/fixtures/list_util.seam |
take/3, drop/3, split_at/4, zip_/3, replicate/3, split_with/3, take_while/3, drop_while/3, span/4, group_by/3, sort_by/3, max_by/3, min_by/3, filter_map/3 |
tests/fixtures/builtins_keywords.seam |
vary/3, unbound_keys/2, signature/3 |
tests/fixtures/builtins_dif.seam |
dif/2, eq/3, dif_t/3 |
tests/fixtures/builtins_call.seam |
Call/N, call_goal/N |
tests/fixtures/coroutining.seam |
call_nth/2, count_all/2, setup_call_cleanup/3, call_cleanup/2, freeze/2, when/2 |
tests/test_python_interop.py |
++() Python interop (13 tests) |
tests/test_dcg.py |
DCG rules, phrase/2, phrase/3 (26 tests) |
tests/fixtures/dcg_grammar.seam |
phrase/2, phrase/3, DCG with non-terminals, inline goals, pushback, negation |
tests/fixtures/clpb_circuit.seam |
sat/1, bool_labeling/1, BoolEq — HalfAdder, FullAdder, PigeonHole |
tests/fixtures/logging_basic.seam |
get_logger, set_level, get_level, is_enabled_for, debug, info, warning, error, critical, log, stream_handler, set_formatter, add_handler, remove_handler |
tests/test_date_time.py (99 tests) |
now, now_utc, today, date, time, datetime, timedelta, date_add, date_sub, date_diff, datetime_string, weekday, date_between, timestamp, datetime_string_iso, date_string_iso |
packages/clausal-yaml/tests/test_yaml_module.py |
read, write, read_all, write_all, read_file, write_file, get |