NucleoidAI/Nucleoid
Tentang
Bahasa logika untuk model dunia ๐ฑ๐๐
Bahasa pemrograman dan runtimePertumbuhan bintang terukur
- dalam 24 jam
- 0
- dalam 7 hari
- 0
- dalam 15 hari
- 0
- dalam 1 bulan
- Mengumpulkan riwayat
Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.
README.md
AsliNucleoid

Logic Language for World Models ๐ฑ๐๐
โก Nucleoid is designed with a minimum-token syntax for logic representation and a declarative execution model, eliminating the need for LLMs to manually manage control flow, state propagation, and other imperative constructs. In addition, Nucleoid is a next-generation logic programming language built on structured objects and their relationships, extending the traditional Knowledge Graph.
- Near-Deterministic: Structured, reliable reasoning.
- Minimum-Token Syntax: Token-efficient declarative syntax.
- Logic Graph: Executable knowledge graph.
https://github.com/user-attachments/assets/3b5a5fa8-9309-473f-ae18-f55e0f63d4da
Quick Start :zap:
Install the CLI from crates.io:
cargo install nucleoid
Run nucleoid from any directory to open the full-screen terminal workspace.
It has Editor and Chat modes, autocomplete for keywords, built-ins and
model properties, and in-session input/result history. F1 selects the
editor; F2 selects chat; Ctrl-Tab switches between them. Both modes
share the same runtime, results, history and unfinished input. Chat is a
code/result transcript, not an AI conversation, and makes no network calls.
Click Text, JSON or Table to inspect a result without running the
program again. Arrays of objects become table rows; other JSON values have
property/value or index/value views.
Object results, including objects nested inside lists, show their contents as
JSON by default in both modes and in the plain REPL; no --json flag is needed.
Other values keep their normal text output unless JSON is explicitly enabled.
Circular objects report a serialization error rather than an object placeholder.
The workspace uses a black and charcoal palette with subtle green focus
accents, an active editor line, and explicit error markers in result history.
The status bar shows the focused pane and its relevant shortcuts, keeping
F5 run and Ctrl-Q quit visible even in compact terminals.
In editor mode, Enter inserts a newline; F5 runs the whole editor. Blank lines
never submit code. In chat mode, Enter sends the input and appends its code,
result and any errors or diagnostics to a scrollable transcript. Shift-Enter
inserts a newline when the terminal reports it distinctly; Ctrl-J inserts an
automatically indented newline in either mode. F5 runs the whole input in
either mode, and bracketed paste never submits code.
Ctrl-Enter also runs on non-Windows terminals that report it distinctly;
Windows treats it as a newline because pasted LF produces the same key event.
Tab accepts autocomplete (or inserts four spaces); with selected text it
indents the selected lines without replacing them. Shift-Tab unindents the
selection or current line. Ctrl-Space opens suggestions.
Ctrl-P / Ctrl-N recalls input while preserving an unfinished draft.
F6 changes the result view, and Ctrl-Up / Ctrl-Down selects earlier results
or jumps to them in chat. Mouse clicks select modes, views and results;
click/drag edits the cursor/selection, and the wheel scrolls individual panes.
Ctrl-C cancels input, Ctrl-Q exits, and .help lists all controls. .editor
and .chat also switch modes. F4 switches between input and transcript in
chat. In editor mode at compact heights, results and diagnostics share a pane;
F4 switches between them without hiding the editor.
Subtle scrollbars mark long results and diagnostics; PageUp / PageDown moves
by the visible rows of the selected pane. Scrolling over autocomplete changes
the selected suggestion without moving the panes behind it.
Long drafts expand the focused input to at most half the terminal, while
result focus returns that space to output. Chat uses a compact input area and
follows new results; Home/End while the transcript is focused jumps to its
start/end. Autocomplete respects strings and comments across lines, so Tab
does not replace text inside them.
nucleoid --plain keeps the line-oriented interface below. Piped stdin or
redirected stdout selects it automatically; file execution and the --json
and --graph flags keep their existing behavior. Teach it that Socrates is
mortal:
> class Human(name: str):
.. this.name = name
..
> $Human.mortal = true
> socrates = Human("Socrates")
> socrates.mortal
true
In plain mode, body lines are prefilled with indentation after the ..
prompt. Tab inserts four spaces; use Backspace to dedent and submit a blank
line to run the complete block. Piped input is not reindented and must include
its own whitespace.
nucleoid --max-steps N bounds programs you did not write, such as models an
LLM generates. It applies to a file run and to each submission in both
interactive interfaces: a run that needs more than N execution steps fails
with TypeError: Step limit exceeded and changes nothing. Without the flag
nothing is limited. The Rust library's Runtime::set_step_limit does the
same; see NUC 185.
C-style comments
Hash (#) line comments, // line comments and non-nesting /* ... */
blocks all work in files and both interactive interfaces:
total = 12 /* units */ / 2 // half of twelve
# hash comments still work
assert(total, 6)
Comments take delimiter priority outside literals, so // is a comment, not
an empty regex; write /(?:)/ for an empty-matching regex (with pattern text
(?:), not an empty string). Strings, template text and nonambiguous regexes
stay literal, and interpolations read comments too. Comments retain newlines
and source positions and cannot join tokens or supply indentation. An
unclosed block reports SyntaxError: Unterminated block comment at its
opening slash. Plain input buffers an open block across blank lines until it
closes or EOF. They no longer need the removed --c-style-comments flag; see
NUC 76.
Is assignments
An assignment can also be written target is value, with quotes optional
around a single word:
status is OPEN
label is "shipped"
assert([status, label], ["OPEN", "shipped"])
OPEN = "open"
assert(status, "open")
delete OPEN
assert(status, "OPEN")
a is 5, o.x is "good" and this.total is total * 2 mean their =
spellings. A value of one bare word reads the variable, class, function or
built-in of that name when one exists, and otherwise stores its own text, so
status above follows OPEN while it is defined. is comparisons such as
if status is OPEN: keep working inside conditions and parentheses. It no
longer needs the removed --is-assignment flag, so a is good assigns
rather than reading as three statements; see NUC 93.
Conditional words
A branch of a conditional is value can be a bare word too:
ready = false
status is OPEN if ready else WAITING
assert(status, "WAITING")
ready = true
assert(status, "OPEN")
a is A if c else B and a is c ? A : B read each branch that is one bare
word as a word value is read: the variable, class, function or built-in of
that name when one exists, otherwise its own text. Conditions and parenthesized
operands are not words, so a is (A if c else B) needs A and B to be
defined. It no longer needs the removed --conditional-words flag; see
NUC 94.
Item words
A list item, a dictionary value or a named argument inside an is value can
be a bare word too:
colors is [RED, GREEN]
pair is {left: RED, right: BLUE}
assert([colors, pair], [["RED", "GREEN"], {"left": "RED", "right": "BLUE"}])
RED = "red"
assert([colors[0], pair.left], ["red", "red"])
colors is [RED, GREEN], glow is {small: DIM, large: BRIGHT}[size] and
first is Light(color=RED, parts=[GREEN, GREEN]) read each item, dictionary
value and named argument that is one bare word as a word value is read,
wherever the list, dictionary or call stands in the value, outside function
bodies, comprehension elements, template interpolations and inner
assignments. Keys keep their text, {A} still reads the variable A, a
parenthesized item such as [(A)] is a reference, and a conditional item
such as [A if c else B] has word branches. It needs no flag, and = keeps
the reference reading, so colors = [RED, GREEN] needs RED and GREEN to
be defined; see NUC 95.
At variables
Inside an is value, @name reads the variable name, never the word:
a is 1
b is @a + 2
RED = "red"
colors is [@RED, GREEN]
assert([b, colors], [3, ["red", "GREEN"]])
@a is read exactly as (a) is, so b is @c + 3 raises
ReferenceError("c is not defined") while nothing defines c, and so does
b is @c, where b is c would store the word "c". The mark works
wherever an operand begins in an is value, outside function bodies,
comprehension elements, template interpolations, inner assignments and
targets, and in the right operand of an is comparison, as in
if state is @OPEN:. Everywhere else a leading @ is still a syntax error,
x@first is still a version, and b is @first still reads as b followed
by is@first; see NUC 96.
Design Theory ๐
Language Reference
docs/README.md is the language reference: statements and state, variables and dependencies, expressions, types and instances, properties, class-level rules, blocks and scope, control flow, functions, transactions, built-in objects, live graph reasoning, error messages, and a syntax summary.
It is assembled from the NUC documents in docs/, indexed by NUC 0 with the conventions in NUC 1. nucleoid.spec.md is normative; where the two disagree, the specification wins.
docs/examples.md covers the same ground as complete programs, each one runnable as written.
The isolated NUC 47 revision uses ordinary class headers:
class Point(x, y) accepts positional, named and positional-then-named calls.
Point(y=4, x=3) binds labels without caller assignments; explicit grouped
assignments retain positional effects. The former star header is removed.
See the paired reference example.
Ordinary function/method calls retain assignment-expression behavior.
A Nucleoid program is a set of statements that remain true. An assignment is not an instruction that runs once and finishes, it is a relationship the runtime records and maintains.
An assignment states a relationship, not a result
a = 1
b = a + 2
a = 3
assert(b, 5)
b is never stale. It is the sum of a and 2, so changing a brings it up to date, and the same holds for properties, class-level rules and everything else the reference covers.
Compound assignments keep their reactive relationships
amount = 10
step = 2
amount += step
assert(amount, 12)
step = 3
assert(amount, 15)
The compound operators +=, -=, *=, /=, and %= are short
spellings of target = target op (expression), not a new mutation mode.
Plain names and dotted paths are supported; old assignment syntax remains
valid. NUC 13 passed independent per-case evaluation.
The crate is now 2.0.0 because the new public lexer token variants affect
downstream exhaustive Rust matches; existing Nucleoid programs remain valid.
Empty types need no placeholder body
class Entity
entity1 = Entity()
$Entity.enabled = true
assert(typeof Entity, List)
assert(entity1.enabled, true)
assert(Entity.length, 1)
A bare class header is equivalent to an indented pass-only body. Optional parameters keep their existing binding behavior and do not create properties automatically. Nonempty bodies and inheritance retain the colon syntax. NUC 14 specifies the accepted syntax and its independent per-case evaluation.
Parent constructors omit empty call parentheses
class Counter:
def init():
this.total = 1
class Counted: Counter
def init():
super
this.total = this.total + 1
counted = Counted()
assert(counted.total, 2)
Bare super is the zero-argument expression super(), running the parent
constructor on the same instance and returning null. Calls with arguments
still use super(arguments...). NUC 16 describes this
candidate shorthand; its proposal status remains Draft.
Object fields reuse their identifier names
amount = 4
label = "meter"
reading = { amount, label }
assert(reading.amount, 4)
assert(reading.label, "meter")
amount = 6
assert(reading.amount, 6)
In this isolated Draft NUC 17 candidate, an ordinary
identifier field in an object expression is shorthand for name: name.
Explicit fields still mix with shorthand; quoted and numeric keys still need
a value. The existing AST, canonical expanded source, scope lookup, dependencies,
snapshots, and transactions are unchanged. This prototype does not change
the accepted language until independent evaluation and caller integration.
Single input named arrows omit parameter parentheses
def square amount => amount * amount
assert(square(3), 9)
assert(square(4), 16)
NUC 18 specifies parameter-parenthesis omission for named
arrow definitions and methods with exactly one untyped ordinary identifier
parameter. Nullary definitions and calls still use parentheses; the optional
untyped and typed/mixed multiple-parameter arrow spellings are
demonstrated below. def square(amount) => amount * amount remains valid.
The body, binding, reactivity, snapshots, receivers and initializer behavior
remain those of NUC 12.
Single input block definitions omit parameter parentheses
def square amount =>
amount * amount
assert(square(3), 9)
assert(square(4), 16)
NUC 19 specifies the same optional single-untyped-identifier
spelling before an indented colon suite, including methods and init.
The sole-return example above uses NUC32's equivalent indented arrow;
def square amount: or def square(amount): with explicit
return amount * amount remains valid. The colon must lead to
a real indented body; inline/brace suites, empty and typed/mixed multiple-parameter
block signatures retain their parentheses. The optional untyped multiple-parameter
indented spelling is demonstrated below. Typed single-parameter indented blocks
have the separate optional spelling below. Block returns, parameter binding, live
dependencies and runtime behavior are unchanged.
Typed single input named arrows omit parameter parentheses
source = 3
def double amount: int => amount * 2
result = double(source)
assert(result, 6)
source = 5
assert(result, 10)
NUC 20 specifies only the immediate
single-identifier typed-arrow header. def double(amount: int) => amount * 2
remains valid with identical parameter/type metadata and named return-block
behavior. Annotations retain their existing handling, not new variable lookup
or type enforcement. Typed bare inline/braced blocks and logical header breaks
are not added. The separate NUC29 extension below adds only typed/mixed
multiple-parameter arrows; calls and NUC18/19 spellings are unchanged.
Numeric clamping keeps values within live bounds
reading = 12
upper = 10
bounded = Math.clamp(reading, 0, upper)
assert(bounded, 10)
reading = 3
assert(bounded, 3)
upper = 2
assert(bounded, 2)
NUC 21 specifies static numeric clamping as the ordered
composition Math.min(Math.max(value, lower), upper) with existing numeric
coercion. Reversed bounds yield the upper bound, numeric NaN propagates,
and omitted inputs supply numeric NaN. Extra argument expressions still run
left to right and participate in the existing undefined gate. The proposal
header records its status; no range-validation error or callable Math method
reference is introduced.
Numeric interpolation blends live values
start = 0
end = 10
weight = 0.5
mixed = Math.lerp(start, end, weight)
assert(mixed, 5)
end = 20
assert(mixed, 10)
weight = 0.25
assert(mixed, 5)
NUC 22 specifies static Math.lerp(start, end, weight);
its header records its status. After intrinsic numeric conversion, it computes
end - start, multiplies by weight, then adds start, using ordinary ordered
arithmetic without fused operations, endpoint shortcuts or weight clamping.
Negative or greater-than-one weights extrapolate; special values and rounding
follow that exact formula. Omissions supply numeric NaN; every supplied
expression runs once left to right, including extras and the existing undefined
gate. Live-null/deferred assignment contexts, shadowing and unsupported Math
method-value reads remain unchanged.
Unit-interval saturation normalizes live progress
# Unit-interval saturation normalizes live progress
ratio = 0.3
progress = Math.saturate(ratio)
assert(progress, 0.3)
ratio = 1.5
assert(progress, 1)
ratio = -0.5
assert(progress, 0)
NUC 23 specifies static Math.saturate(value) as exactly
ordered Math.clamp(value, 0, 1) through
the accepted min/max folds, with intrinsic numeric conversion, not host range
validation or endpoint shortcuts. Omission produces numeric NaN; extra
expressions still run once left to right and retain reads, effects and the
existing undefined gate. Live-null/deferred handling, rollback, namespace
shadowing and unsupported method-value reads remain unchanged. The normative
contract is Reactive unit-interval saturation.
Typed block definitions preserve live bounded progress
# Typed block definitions preserve live bounded progress
ratio = 0.3
def normalize amount: ArbitraryType =>
Math.saturate(amount)
progress = normalize(ratio)
assert(progress, 0.3)
ratio = 1.5
assert(progress, 1)
ratio = -0.5
assert(progress, 0)
NUC 24 describes the optional single typed parameter spelling
before a real indented suite. def normalize(amount: ArbitraryType): with the
same body remains valid. The immediate name/colon/annotation/colon prefix and
real indent preserve the full parameter metadata and named block AST.
Annotations introduce no lookup or runtime type constraint. Header-line breaks,
inline/braced bare suites and other parameter/type forms are not added; calls,
NUC18/19/20 spellings, block returns and live dependencies are unchanged.
Logical compound assignments preserve short-circuiting
def fail():
throw "UNREACHABLE"
enabled = true
enabled ||= fail()
assert(enabled, true)
disabled = false
disabled &&= fail()
assert(disabled, false)
Accepted NUC 26 defines optional &&= and ||=.
They lower exactly to target = target && (rhs) and
target = target || (rhs), not JavaScript-style conditional writes.
A standing assignment installs its relationship even when logical evaluation
skips the right operand. Existing =, &&, ||, and, or, and arithmetic
compounds remain supported; snapshots, dependencies and rollback are unchanged.
The public lexer enum additions require a human-owned API semver decision;
this revision changes no project version.
Named arrows can omit parentheses around multiple parameters
def add left right => left + right
assert(add(2, 3), 5)
def scaled left right factor => (left + right) * factor
assert(scaled(2, 3, 4), 20)
Accepted NUC 27 adds only a complete
comma-separated list of two or more untyped ordinary identifiers immediately
followed by => on the same logical header line, including methods and init.
def add(left, right) => left + right remains valid and exactly equivalent.
Trailing bare commas, bare inline/braced blocks, defaults,
destructuring, rest parameters and return annotations are not added.
Typed/mixed arrow lists have the separate NUC29 spelling below.
No logical newline, semicolon or comment-induced break is skipped. Calls retain
their parentheses and anonymous arrows retain their existing grammar; the
single-parameter typed and block alternatives above remain unchanged.
Indented blocks can omit parentheses around multiple parameters
def add left right =>
left + right
assert(add(2, 3), 5)
NUC 28 adds the optional spelling of
def add(left, right): with the same indented body, including methods and init.
The complete comma-separated list contains two or more untyped ordinary
identifiers on one logical header line. After the colon require an immediate
newline or indent and a real indent after only normal newline/semicolon layout;
a colon immediately followed by a semicolon does not qualify. Blank/comment
lines before a genuine body keep their existing grammar.
NUC30 separately adds typed/mixed multiple indented headers below; NUC28's
identifier-only forms remain unchanged. Inline/braced bare suites, trailing bare
commas and logical breaks within the header remain unsupported. Parenthesized
forms, arrows, single-parameter guards and calls are unchanged. Block returns,
scope, receivers, live relationships, snapshots and rollback retain the
parenthesized behavior; there is no implicit last-expression return.
Typed multiple parameter named arrows can omit parentheses
def add left: int, right: int => left + right
assert(add(2, 3), 5)
- NUC 29 adds this optional arrow spelling;
def add(left: int, right: int) => left + rightremains valid and exactly equivalent, including methods andinit. - Require at least two ordinary identifier parameters, with at least one
existing
: Identifierannotation for the new typed/mixed forms. Untyped multiple lists retain NUC27 behavior; annotations stay metadata, not runtime type checks. Mixed lists may annotate any parameter. - The complete comma-separated header must immediately end in
=>, without logical breaks or skipped separators. NUC29 does not itself add blocks; NUC30's separate typed/mixed indented spelling follows below. Bare inline/braced suites, trailing bare commas, new parameter/type grammar and call-site omission remain unsupported. Single guards and NUC28 untyped blocks are unchanged. - Binding, named return-block lowering, expression bodies, receivers, reactivity, snapshots, graph dependencies and rollback remain unchanged.
Typed multiple parameter blocks can omit parentheses
def add left: int, right: int =>
left + right
assert(add(2, 3), 5)
- NUC 30 describes the optional spelling of
def add(left: int, right: int):with the same real indented body, including methods andinit. Mixed headers such asdef add left: int, right:also preserve the complete named block and ordered annotation metadata. - Require at least two ordinary identifier parameters, with at least one
existing
: Identifierannotation for the new forms. Entirely untyped lists remain NUC28 behavior; annotations introduce neither lookup nor type checking. - Scan the complete header without consuming tokens or skipping logical breaks.
The suite colon must immediately lead to a newline or indent and a real indent
after only normal newline/semicolon layout;
:;never qualifies. A final untyped parameter's colon belongs to the suite, not an annotation. - Parenthesized forms, NUC24 single typed blocks, NUC28 untyped blocks, NUC29 arrows and calls remain unchanged. Bare inline/braced suites, trailing commas, new type/parameter grammar and return annotations are not added.
- Block returns, local shadowing, receivers, reactive inputs, live aliases, definition snapshots, redefinition and rollback keep the parenthesized behavior, with no implicit final-expression return.
Named source loops can bind it implicitly
class Task
task = Task()
task.done = false
for Task:
it.done = true
assert(task.done, true)
- Accepted NUC 31 specifies optional
for NAME:with a genuine indented body as exactlyfor it of NAME:with that same body.NAMEis one ordinary identifier; the body binds each visited value to localit, restoring any outer binding afterward. - The source is evaluated once: class populations and lists visit only current registered typed instances in order. Primitives, null elements and plain objects in lists are skipped; this is not general array iteration or a standing rule. A named noniterable source raises the existing TypeError.
- The NUC 51 candidate additionally accepts String sources as scalar snapshots, without changing that object-only List policy.
- The NUC 127 draft also permits
for NAMEwithout its colon before that same genuinely indented body.NAMEis exactly one RustIdentifier, including contextual names such aswhile,enumandmodel. - Require the immediate identifier and optional colon, then a newline or indent
and a real indent after only normal newline/semicolon layout. No header-line
;or:;, inline/braced/missing-indent or expression-source shorthand is added. - Explicit
for variable of expressionandfor variable in expressionremain valid with their existing arbitrary expressions and colon-required suite forms. Two-name entry loops also keep their colon. Nested scopes, receivers, returns, snapshots, graphs and rollback are unchanged.
Reasoning stays live too: why b explains its dependencies, and affects a
reports its downstream impact. Both update when relationships are rewritten,
added, or removed, even if their values stay the same. The implemented stages of
NUC 11 cover selections, pipelines, and structural subscriptions;
its later stages remain proposals.
Every example in the reference is executable: tests/reference.md is its executable form and runs under cargo test, as do the snippets on this page.
|
Welcome! Iโve been expecting youโ"Skynet was gone. And now one road has become many." ๐
The future is building up! World Models are now an emerging field within AI communities and marks a crucial milestone on the journey to AGI. Unfortunately, existing symbolic AI and knowledge graphs lack advancement in today's AI landscape. Nucleoid is revolutionizing knowledge graphs with declarative, logic-based, contextual runtime, which can be integrated with ANNs to lay a robust foundation for the next leap forward imao.
Can Mingir
|
Neuro-Symbolic AI
A world model is what a system knows about a domain: which entities exist, how they relate, which rules hold across all of them, and what follows once something changes. In an LLM that model is implicit, spread across the weights, and that is where hallucination begins, because a model that cannot be inspected cannot be corrected and cannot be held to its own rules. Neuro-Symbolic AI is how the model is made explicit, and it is why the two components below are complementary rather than competing.
Neuro-Symbolic AI is an approach that integrates the strengths of both neural networks and symbolic AI to create systems that can learn from data and also reason logically. By combining these two components, Neuro-Symbolic AI aims to leverage the intuitive, pattern-recognition capabilities of neural networks along with the logical, rule-based reasoning of symbolic AI. This integration offers a more holistic AI system that is both adaptable and able to explain its decisions, making it suitable for complex decision-making tasks where both learning from data and logical reasoning are required. Hereโs how it breaks down:
Neural Networks: The Learning Component
Neural networks in Neuro-Symbolic AI are adept at learning patterns, relationships, and features from large datasets. These networks excel in tasks that involve classification, prediction, and pattern recognition, making them invaluable for processing unstructured data, such as images, text, and audio. Neural networks, through their learning capabilities, can generalize from examples to understand complex data structures and nuances in the data.
Symbolic AI: The Reasoning Component
The symbolic component of Neuro-Symbolic AI focuses on logic, rules, and symbolic representations of knowledge. Unlike neural networks that learn from data, symbolic AI uses predefined rules and knowledge bases to perform reasoning, make inferences, and understand relationships between entities. This aspect of AI is transparent, interpretable, and capable of explaining its decisions and reasoning processes in a way that humans can understand.
World Models: The State Component
Neural networks learn and symbolic AI reasons, but reasoning needs something to reason over, and that is the world model: the entities, relationships and rules a system currently holds to be true. In Nucleoid the model is not a passive knowledge base that is read from and written to, it is a logic graph that the runtime keeps true on its own. A rule stated over a type holds for every instance of it, including instances created long afterwards, and a change to any value propagates to everything derived from it, so the model is never left holding a fact together with its own stale consequence.
Rules also decide which worlds are admissible. A statement and every rule it triggers form a single transaction, and if any rule rejects the change, the transaction is rolled back and the state is exactly as it was, so an update that would contradict the model is never partially applied. A world model built this way cannot drift into a state that violates its own laws.
This is what makes the model usable by a language model. It is written incrementally, one statement at a time, in a syntax that costs few tokens, and it can be queried long after it was written, by another session or another model, because the meaning lives in the graph rather than in the context window.
Declarative Language: 6GL Programming Language
Nucleoid is a 6GL programming language, and Nucleoid acts as the ubiquitous language in Neuro-Symbolic AI for specifying the desired outcomes of a program without detailing the procedural methods to achieve these outcomes. This type of language is essential for articulating logical rules, constraints, and relationships that underpin symbolic reasoning within these systems. It supports the formulation of structured knowledge bases and facilitates logical reasoning tasks, enabling systems to deduce, infer, and respond to queries based on established rules. Moreover, declarative languages are instrumental in integrating the outputs of neural networks into symbolic reasoning frameworks, marrying data-driven learning with rule-based logic. Their widespread use enhances the transparency, explainability, and modularity of AI systems, while also boosting their efficiency in domains heavily reliant on rule-based operations.
Declarative Logic in Symbolic Reasoning
Declarative logic is a subset of declarative programming, a style of building programs that expresses the logic of a computation without describing its control flow. In declarative logic, you state the facts and rules that define the problem domain. The runtime environment or the system itself figures out how to satisfy those conditions or how to apply those rules to reach a conclusion. This contrasts with imperative programming, where the developer writes code that describes the exact steps to achieve a goal.
Symbolic reasoning refers to the process of using symbols to represent problems and applying logical rules to manipulate these symbols and derive conclusions or solutions. In AI and computer science, it involves using symbolic representations for entities and actions, enabling the system to perform logical inferences, decision making, and problem-solving based on the rules and knowledge encoded in the symbols.
By integrating Nucleoid into Neuro-Symbolic AI, the system benefits from enhanced interpretability and reliability. The declarative logic and rules defined in Nucleoid provide clear explanations for the AI's decisions, making it easier for users to understand and trust the system's outputs. Furthermore, the explicit reasoning capabilities help ensure that decisions are made based on logical principles, adding a layer of reliability and consistency to the AI's behavior.
Plasticity in Neuro-Symbolic AI
In the realm of Neuro-Symbolic AI, Plasticity is an important element for the system's ability to modify and optimize its connections in response to new information. This concept is inspired by neuroplasticity in biological brains, where neurons can strengthen or weaken their connections based on activity, enabling learning and memory.
- Dynamic Knowledge Base: Neuro-Symbolic AI systems dynamically update their knowledge base as they encounter new scenarios or corrections to their previous knowledge. This continuous updating process allows the systems to remain relevant and accurate over time.
- Adaptive Logic and Reasoning: The AI system can modify its symbolic rules and reasoning strategies to better match observed data or outcomes, enhancing its decision-making and problem-solving abilities.
- Generalization and Specialization: Through plasticity, the system can generalize from learned experiences to new, unseen scenarios or specialize in certain domains by fine-tuning its parameters or rules based on specific data inputs.
The idea of plasticity in AI, especially in logic-based systems like those in Neuro-Symbolic AI, enhances the capability of machines to not only perform tasks based on fixed rules but also to evolve those rules and adapt their reasoning over time, much like the cognitive flexibility of living things.
Learn more at nucleoid.com/docs/get-started
Nucleoid's Taxonomy
Nucleoid is an implementation of symbolic AI for declarative (logic) programming at the runtime. As mentioned, the declarative runtime environment manages the state and stores each transaction in the built-in data store by declaratively rerendering statements and building the knowledge graph (base) as well as an execution plan.
The declarative runtime isolates a behavior definition of a program from its technical instructions and executes declarative statements, which represent logical intention without carrying any technical detail. In this paradigm, there is no segregation regarding what data is or not, instead approaches how data (declarative statement) is related with others so that any type of data including business rules can be added without requiring any additional actions such as compiling, configuring, restarting as a result of plasticity. This approach also opens possibilities of storing data in the same box with the programming runtime.
|
|
|---|
In short, the main objective of the project is to manage both of data and logic under the same runtime. The declarative programming paradigm used by Nucleoid allows developers to focus on the business logic of the application, while the runtime manages the technical details.This allows for faster development and reduces the amount of code that needs to be written. Additionally, the sharding feature can help to distribute the load across multiple instances, which can further improve the performance of the system.
Named arrows can indent a single expression
def square value =>
value * value
assert(square(4), 16)
NUC 32 specifies an optional genuinely indented expression
after the existing named =>. It is exactly the colon suite containing
return value * value; existing inline arrows and colon suites remain valid.
It does not add an arbitrary statement suite or an implicit final-statement
return, and nullary definitions still require ().
Earlier sole-return block examples above use this equivalent layout where
applicable; existing colon suites, including multi-statement bodies, are
unchanged alternatives.
Cubic smoothstep keeps input changes live
value = 0.25
unit = Math.saturate(value)
eased = Math.smoothstep(0, 1, value)
assert(unit, 0.25)
assert(eased, 0.15625)
value = 0.75
assert(eased, 0.84375)
- Accepted NUC 33 defines static
Math.smoothstep(lower, upper, value), with bounds before the value. - The independent
unitcontrol remains live; the intrinsic normalizes and clamps before applying the ordered cubic, retaining existing special-value, deferred-read and transactional behavior.
Indented else suites keep live inputs concise
enabled = false
raw = 2
if enabled:
display = raw
else
display = raw + 1
assert(display, 3)
enabled = true
assert(display, 2)
raw = 5
assert(display, 5)
- Accepted NUC 34 permits this optional final-
elsespelling only before a real indented body.else:remains valid and equivalent. - This legacy control deliberately retains its condition colon.
NUC 49 also permits omission for genuine-indented
if/else ifsuites; inline, semicolon-separated and braced alternatives still require their accepted colons. A header-line semicolon cannot qualify. - Nested branch association, live inputs, scope, returns and rollback are
unchanged. Strings and comments containing
else:are not rewritten.
Quintic smootherstep keeps input changes live
value = 0.25
unit = Math.saturate(value)
eased = Math.smootherstep(0, 1, value)
assert(unit, 0.25)
assert(eased, 0.103515625)
value = 0.75
assert(eased, 0.896484375)
- Accepted NUC 35 adds static
Math.smootherstep(lower, upper, value)beside unchanged cubicMath.smoothstep. The independentunitcontrol remains live. - Normalize and clamp before the exactly ordered quintic; do not clamp its result, which can round beyond the unit interval. Existing numeric coercion, special values, deferred reads, argument effects and rollback are preserved.
Floor fractional parts keep negative inputs live
value = -1.25
whole = Math.floor(value)
fraction = Math.fract(value)
assert(whole, -2)
assert(fraction, 0.75)
value = 3.5
assert(fraction, 0.5)
- Accepted NUC 36 adds static
Math.fract(value)as intrinsic numeric conversion followed by floor and subtraction, retaining the independentwholecontrol and accepted floor-subtraction spelling. - Negative fractions subtract floor, not truncation. Tiny negative inputs can
round to exactly one, so the result is not promised strictly in
[0, 1). Numeric coercion, ignored-extra effects/reads, deferral and rollback remain.
Named arrow parameters can omit every comma
def add left right => left + right
assert(add(2, 3), 5)
def scaled left right factor => (left + right) * factor
assert(scaled(2, 3, 4), 20)
- NUC 37 adds optional all-comma-free bare named arrows with at least two untyped ordinary identifiers on one logical header line. The comma-bearing and parenthesized forms remain valid. Typed/mixed lists still need commas; the separate NUC40 below adds the wholly untyped, genuinely indented colon-suite counterpart.
Inverse interpolation keeps live inputs unclamped
start = 0
end = 8
sample = 2
weight = Math.inverseLerp(start, end, sample)
assert(weight, 0.25)
sample = 12
assert(weight, 1.5)
end = 16
assert(weight, 0.75)
- Accepted NUC 38 adds only static
Math.inverseLerp(start, end, value), the unclamped ordered composition(value - start) / (end - start)with intrinsic numeric conversion. - Descending ranges and results outside
[0, 1]are intentional. Equal endpoints, nonfinite values and span overflow follow separate subtraction, subtraction and division, without endpoint shortcuts or scaling. - The accepted arithmetic spelling remains available. Ignored-extra reads, effects, strict failures, live-null deferral and rollback remain unchanged; the authoritative contract defines the complete numeric and compatibility rules.
Range remapping keeps live values unclamped
start = 0
end = 8
targetStart = 0
targetEnd = 100
sample = 2
mapped = Math.remap(start, end, targetStart, targetEnd, sample)
assert(mapped, 25)
sample = 12
assert(mapped, 150)
end = 16
assert(mapped, 75)
- Accepted NUC 39 adds only static
Math.remap(start, end, targetStart, targetEnd, value), the unclamped numeric composition of accepted inverse interpolation and interpolation. - Keep six separate ordered operations, with no rescaling, range ordering, endpoint shortcuts or fused arithmetic. Both ranges may descend.
- The accepted nested spelling remains available. Its target arguments run before inner source arguments; the new call instead evaluates its listed five arguments left to right. Pure-read paired cases preserve behavior.
- Ignored-extra effects/reads, live-null deferral and rollback use unchanged machinery; the authoritative contract gives the full rules.
Indented blocks can omit every parameter comma
def add left right:
return left + right
left = 2
right = 3
total = add(left, right)
assert(total, 5)
left = 5
assert(total, 8)
- NUC 40 adds only the optional complete
def add left right:header before a real indented statement suite.def add left, right:anddef add(left, right):with the same body remain valid and equivalent. - Require at least two wholly untyped ordinary identifiers and omit all parameter commas or none. The final colon and real indentation are required; typed/mixed lists, inline/braced bare suites, calls and anonymous functions do not gain comma omission. Explicit, bare and absent returns are unchanged.
- The authoritative contract keeps all accepted syntax, body punctuation, live dependencies and rollback.
Reactive flat mapping
Flat mapping produces zero or many results per input
numbers = [1, 2, 3]
def copies(value):
if value > 1:
return [value, value * 10]
return []
expanded = numbers.flatMap(copies)
assert(expanded, [2, 20, 3, 30])
assert(numbers, [1, 2, 3])
numbers.push(4)
assert(expanded, [2, 20, 3, 30, 4, 40])
- Accepted NUC 41 provides one read-only
flatMap(callback)query for lists and class populations. - Each snapshotted item invokes the callback once, in order, with one argument. A returned list contributes one level of items; other values contribute one item. Order, duplicates and live object/function identities remain.
- Callback validation, eager supplied arguments (including extras), real
null/deferred reads, dependencies and transactional errors use existing
machinery. Functions and properties named
flatMapremain ordinary names. - Existing
map,reduceandconcatstay supported. See the authoritative contract for snapshot timing and the distinction between returning null and actually reading it.
Reactive literal string replacement
Literal replacements normalize every occurrence
source = "todo:one|todo:two|todo:one"
normalized = source.replaceAll("todo:", "")
assert(normalized, "one|two|one")
source = "todo:three"
assert(normalized, "three")
assert(source, "todo:three")
- Accepted NUC 42 adds a read-only string-instance
replaceAll(search, replacement)for literal, non-overlapping matches. - Replacement text is literal too; empty search inserts at Unicode scalar boundaries, including both ends (one boundary for an empty receiver).
- Inputs retain ordinary reactive reads, snapshots, argument evaluation and
transactional errors. Existing first-only
replaceand split/join recipes remain valid. See the root contract.
Direct conditional alternatives
Conditional alternatives omit the second keyword
def label(state):
if state == "done"
return "archive"
else state == "ready"
return "send"
else:
return "wait"
state = "ready"
result = label(state)
assert(result, "send")
state = "done"
assert(result, "archive")
state = "queued"
assert(result, "wait")
- NUC 43 optionally omits the second
ifonly before a complete condition with a genuine indented body.elif condition:is the same optional spelling through the existingelifalias forelse. - NUC 49 additionally makes the header colon optional
for initial
if, explicitelse if/elif if, and these direct alternatives, only before a genuine indented suite. The CLI recognizes initial colon-free headers and autoindents without treating literal/comment punctuation as syntax. - Explicit
else ifremains supported, including inline/braced bodies. Finalelse:/elif:and genuine-indented colon-free final alternatives retain their unconditional meaning. No standalone or inline direct conditional alternative is added. - Parsing lowers to the same nested conditional, keeping first-match evaluation, live dependencies, scopes, returns and rollback unchanged. See the root contract.
Comma-free explicit object properties
Explicit object fields omit redundant commas
# Explicit object fields omit redundant commas
name = "sensor"
reading = 4
record = {name: name reading: reading unit: "C"}
assert(record.name, "sensor")
assert(record.reading, 4)
reading = 9
assert(record.reading, 9)
- NUC 44 permits the next explicit
string, identifier or numeric key followed immediately by
:after the preceding value has been fully parsed. Existing commas retain priority. - Comma-bearing forms remain valid; shorthand, lists, calls, parameters and block syntax do not gain general comma omission. Canonical records still render with quoted keys and commas.
- Live dependencies, aliases, snapshots, class receivers and transaction behavior remain unchanged. See the root contract.
- The number-led spelling extends the post-value guard only after all original whole-input parses fail; it does not change the ordinary value expression's priority.
Colon-led assertion statements (Accepted NUC 45)
Assertions have a compact statement spelling
# Assertions have a compact statement spelling
status = "ready"
record = {status: status}
assert: record.status, "ready"
status = "sent"
assert: record.status, "sent"
- Accepted NUC 45 adds an optional statement spelling
for the existing two-argument
assert(actual, expected)helper. - The old call syntax remains supported, including expression uses. This is an equality check, not a truthiness assertion or generic bare call.
- Both forms use the same AST, evaluation order, failure collection, counters, transactions and exclusion from program results and model nodes. See the root contract.
Colon-free indented exception suites (Accepted NUC 46)
Indented error recovery omits redundant colons
# Indented error recovery omits redundant colons
quantity = 3
total = quantity * 2
try
quantity = 5
throw "CANCEL"
catch error
assert(error, "CANCEL")
assert(quantity, 3)
assert(total, 6)
- Accepted NUC 46 permits either exception-suite colon to
be omitted only when its complete existing header has a real indented body.
try:andcatch error:with the same bodies remain valid and equivalent. - Default
catch, namedcatch issueand parenthesizedcatch(issue)keep the existing bindings. Inline/braced suites still require their colons. - The native REPL buffers a complete lexical bare
tryheader through its catch until blank-line commit or EOF, including trailing header comments. - Recovery uses the same transactional rollback and live dependency model, not a new error API, scope or continuation rule. See the root contract.
Degree to radian conversion follows live inputs
degrees = 180
radians = Math.toRadians(degrees)
assert(radians, Math.PI)
degrees = 90
assert(radians, Math.PI / 2)
The NUC 50 candidate adds only static
Math.toRadians(value), retaining the acceptedvalue * (Math.PI / 180)arithmetic. Intrinsic conversion multiplies by the separately computedf64factorPI / 180.0, not by PI before division.Supplied expressions, including ignored extras, retain left-to-right evaluation, reactive reads, errors and the existing supplied-Undefined gate. See the root contract.
NUC 142 adds native static
Math.copySign(value, sign). Intrinsic first-two-value conversion copies the non-NaN sign bit without changing magnitude bits, including signed zeros, subnormals and infinities. A NaN or omitted sign yields numeric NaN; NaN payload/sign bits are not promised. Ignored extras retain eager reads, effects and strict errors; any top-level Undefined still gates the call before conversion. Live-null deferral, shadowing, class rules and rollback remain unchanged. No aliases, receiver methods or syntax are added. See the root contract.NUC 143 adds only native static
Math.square(value): intrinsically convert the first value, then compute exactlyfirst * firstwith ordinary multiplication, not exponentiation. Either zero sign squares to positive zero; overflow, underflow, infinities and NaN classification retain multiplication's behavior. Extras still evaluate once left to right with effects, strict errors and subscriptions; any supplied top-level Undefined gates the call before conversion. Omission gives numeric NaN. Live/parameter-null deferral, shadowing, native method-value reads and existing rollback remain unchanged. See the root contract and argument-dependency case.The NUC 146 candidate adds native static
Math.cube(value): intrinsically convert the first value, square it, then multiply by that same value, using two separate ordinary multiplications. Ordered rounding, negative zero, signed underflow, overflow and nonfinite classification follow those operations, not a universal** 3alias. All arguments evaluate once left to right; ignored extras retain effects, strict errors and subscriptions without conversion. The supplied top-level-Undefined gate, live/parameter-null deferral, shadowing, captures and transaction behavior remain unchanged. No aliases or syntax are added. See the root contract and argument-dependency case.
String iteration
String iteration reads characters directly
word = "NUC"
letters = []
for character of word:
letters.push(character)
assert(letters, ["N", "U", "C"])
- The NUC 51 candidate extends the existing
of,inand named-source implicit-itloops to Strings, without new syntax. - Evaluate the source once and snapshot one String per Unicode scalar in source order; an empty String runs no body. Bodies remain one-shot and imperative, with ordinary scopes, receivers, returns and rollback.
- This is not byte, UTF-16 or grapheme traversal and does not normalize text. Primitive lists still skip their entries; split/map expressions remain available but return different intermediate values. See the root contract.
Read-only state versions
Named state versions read earlier variable values
name = "Can"
name = "Daphne"
firstName = name@first
lastName = name@last
previousName = name@previous
assert(firstName, "Can")
assert(lastName, "Daphne")
assert(previousName, "Can")
- NUC 53 defines automatic retention of actual
changes to variable and object-property storage, including reactive updates.
@0is the first version;@first,@lastand@previousselect literal positions without mirror lists. Equal writes add nothing. - Selectors are read-only, oldest-first and never negative. Histories persist
until deletion/clear and roll back with state. Returned objects keep normal
identity semantics, not deep snapshots. Ordinary fields named
first,lastandprevious, negative list indexes and.valueremain unchanged. See the root contract.
Literal parameter defaults
Literal defaults fill omitted trailing arguments
def total(quantity, unit = 5) => quantity * unit
one = total(1)
two = total(2)
three = total(3)
assert(one, 5)
assert(two, 10)
assert(three, 15)
- Parenthesized user-defined signatures may supply immutable scalar literals for absent arguments. Explicit null/falsy arguments are not replaced; annotations and bare signatures keep their existing behavior.
- Defaults are finite signed numbers, quoted Strings, Booleans or null, not expressions or shared mutable values. See the root contract.
Class-level state version anchors
Class conditionals shift each instance from its first recorded coordinates
class Obj(x: int, y: int, orientation: int):
this.x = x
this.y = y
this.orientation = orientation
if $Obj.orientation == 180:
$Obj.tag = "l4214"
$Obj.x = $Obj.x@first - 1
$Obj.y = $Obj.y@first - 1
first = Obj(10, 20, 180)
second = Obj(30, 40, 180)
assert([first.x, first.y, first.tag], [9, 19, "l4214"])
assert([second.x, second.y, second.tag], [29, 39, "l4214"])
first.orientation = 0
first.orientation = 180
assert([first.x, first.y], [9, 19])
assert([first.x@0, second.x@first], [10, 30])
- Draft NUC 55 extends accepted NUC53 histories to stable class self-anchors:
@firstmeans the instance/property slot's first recorded value, not the value when its rule activates.@0is the same anchor. - Ordinary class property rules can use fixed self-history too. Missing
fixed self-entries wait for actual input. Moving
@last/@previousreads retain accepted imperative conditional effects; direct moving self-rules still raise Circular Dependency. Histories stay read-only, slot-owned and transactional. See the rootnucleoid.spec.mdClass-level state version anchors contract. - With NUC 85, a class rule may also read another
property of its own receiver at a fixed position, so
$Box.width = $Box.height@firstwith$Box.height = $Box.width@firstswaps each box's first recorded values. Such a cycle stands only when every read on it is fixed; a live or moving read still raises Circular Dependency. Fixed reads stay tracked through deletion and recreation. See Fixed cross-property class anchors innucleoid.spec.md.
Reactive base two powers
level = 2
multiplier = Math.exp2(level)
assert(multiplier, 4)
level = 5
assert(multiplier, 32)
- Accepted NUC 56 names
Math.exp2(value)while retaining the exact acceptedMath.pow(2, value)numeric operation and reactive call behavior. OrdinaryMath.powremains supported. - The NUC 100 candidate adds unshadowed static
Math.cot(value), exactly the existing1 / Math.tan(value)in radians: intrinsic conversion, tangent, then reciprocal with the same rounding. Missing-first NaN, signed-zero infinities, ignored-extra evaluation and dependencies, live-null/parameter deferral, shadowing and rollback retain Math's existing behavior. It adds no syntax or callable method reference. See the contract and reactive direction example. - The NUC 141 names only native static
Math.csc(value), exactly the accepted reciprocal of sine in radians. Intrinsic conversion, rounded sine and reciprocal stay in that order; zero signs retain signed infinities, and PI uses the actual rounded sine. Eager extras, the supplied-Undefined gate, live-null/parameter deferral, dependency subscriptions, shadowing and rollback remain unchanged. See the contract and argument-dependency case.
Thin arrows and lambdas spell the same callbacks
limit = 2
items = [1, 2, 3]
over = items.filter(item -> item > limit)
under = items.filter(lambda item: item <= limit)
assert(over, [3])
assert(under, [1, 2])
limit = 1
assert(over, [2, 3])
assert(under, [1])
- NUC 57 accepts
->wherever=>is accepted, including nameddefheaders, and Python-stylelambda first, second: expressionas exactly(first, second) => (expression).=>stays canonical, andlambdais still an ordinary name wherever accepted syntax owns its colon.
Conditional expressions
Conditional expressions pick live values in either spelling
price = 120
shipping = 0 if price > 100 else 5
label = price > 100 ? "free shipping" : "standard"
assert(shipping, 0)
assert(label, "free shipping")
price = 40
assert(shipping, 5)
assert(label, "standard")
- NUC 59 adds
condition ? consequent : alternateand Python'sconsequent if condition else alternate. Both build one expression that evaluates its condition once and then only the selected branch, so a falsy consequent such as0works whereprice > 100 && 0 || 5would always give5. - The declarations stay live and switch branches when the condition changes.
ifstatements, including one written after an expression on the same line, keep their accepted readings. See the root contract.
Nullish coalescing
Nullish coalescing defaults unknown values and keeps zero
price = null
shown = price ?? "TBD"
discount = 0
rate = discount ?? 10
assert(shown, "TBD")
assert(rate, 0)
price = 12
assert(shown, 12)
- NUC 60 adds
left ?? right, which yieldsleftunless it is null and otherwise its default.price ?? "TBD"stays live, anddiscount ?? 10keeps a real0wherediscount || 10would give10. - A null read inside
leftno longer settles the declaration tonull, as it does forprice || "TBD", so??is the expression-level way to default an unknown value. See the root contract.
Instance list ranges and list queries
Instance lists slice like lists and answer live queries
class Task(title):
this.title = title
plan = Task("plan")
build = Task("build")
recent = Task[-1:]
newest = Task.at(-1).title
assert(recent, [build])
ship = Task("ship")
assert(recent, [ship])
assert(newest, "ship")
assert(Task.list(), [plan, build, ship])
assert(Task.findLastIndex(task => task.title.length == 4), 2)
- NUC 61 lets a class's instance list take list ranges,
such as
Task[-1:]andTask[:], and lists every instance withTask.list()orTask.all(). Each stays live as instances are created. - Lists and instance lists gain JavaScript's
at,lastIndexOf,findIndex,findLastandfindLastIndexbeside the existingincludes,indexOf,concatandslice. All of them are read-only queries that follow the list, the population and what their callbacks read. See the root contract.
Quantifiers
Quantifiers keep claims about every instance live
class Task(skill):
this.skill = skill
class Worker(skill):
this.skill = skill
Task("rust")
Task("docs")
Worker("rust")
covered = all t in Task: any w in Worker: w.skill == t.skill
assert(covered, false)
Worker("docs")
assert(covered, true)
- NUC 62 adds
all NAME in COLLECTION: CONDITIONandany NAME in COLLECTION: CONDITION. They quantify over class instances, lists and reasoning selections, and they nest, because a condition reads the binders around it. coveredis a live declaration: it re-evaluates when a task or a worker is created or a skill changes. Everywhere elseallandanystay ordinary names. See the root contract.
Exponentiation
Exponentiation keeps compound growth live
rate = 0.5
years = 2
balance = 100 * (1 + rate) ** years
assert(balance, 225)
years = 3
assert(balance, 337.5)
rate = 1
assert(balance, 800)
- NUC 64 adds
base ** exponentand its compound assignmenttarget **= exponent.a ** bgives exactlyMath.pow(a, b), binds tighter than*and groups to the right, so2 ** 3 ** 2is512. balanceis a live declaration: it re-evaluates whenrateoryearschanges. As in Python,-x ** 2means-(x ** 2); write(-x) ** 2to raise a negative base. See the root contract.
Hypotheticals
Suppose blocks answer what-if questions without changing the model
price = 80
shipping = price >= 100 ? 0 : 9
total = price + shipping
suppose price = 100: assert: shipping, 0
upgrade = suppose price = 120: total
assert: upgrade, 120
assert: total, 89
price = 90
assert: upgrade, 120
assert: total, 99
- NUC 65 adds
supposeblocks.suppose PREMISE:runs the premise and its suite in a hypothetical world, where rules propagate as usual, and then discards everything they did.TARGET = suppose ...keeps the value of the block's last expression as a snapshot, soupgradestays120whenpricechanges later. - A thrown error, a
returnor a normal end all roll the block back, and values leave it as plain data. Everywhere elsesupposestays an ordinary name. See the root contract.
Value assignment
Value assignments take an action once while declarations stay live
price = 4
quantity = 3
quote = price * quantity
paid := price * quantity
price = 5
quantity = 2
assert: quote, 10
assert: paid, 12
assert: (why paid)[0].rule, "paid = 12"
- NUC 66 adds the value assignment
TARGET := EXPR, as in Go and Pascal. It evaluates the expression once, records no dependency, and stores the result as a stated fact, exactly as if the value had been written as a literal with=. quoteis a declaration, a law that followspriceandquantity.paidis an action taken at one moment, so it keeps12, andwhyshows the stated literal. See the root contract.- NUC 144 adds
TARGET ??:= EXPRfor a one-shot fill: only Null or Undefined takes the same action. Every other value skips the RHS and preserves the target's standing law, identity and history. Guard and action reads stay isolated from enclosing rules; see Nullish value assignment. - NUC 151 adds
TARGET &&:= EXPRfor a one-shot action only when the current target is truthy. Falsy skips evaluate no RHS and preserve the target's law, identity and history. Guard and action reads are isolated; a taken action retains:='s top-level filing versus imperative-body carry-out distinction. See Truthy value assignment.
List and population sums
Sums keep totals live as instances change
class Item(price, qty):
this.price = price
this.qty = qty
pen = Item(2, 10)
ink = Item(30, 2)
total = Item.sum(item -> item.price * item.qty)
units = Item.sum(item -> item.qty)
assert(total, 80)
assert(units, 12)
ink.qty = 3
Item(5, 1)
assert(total, 115)
assert(units, 14)
- NUC 68 adds
sum()andsum(selector)to lists and class instance lists.Item.sum(item -> item.price * item.qty)totals every instance, adding left to right from0, and an empty list or class totals0. totalandunitsare live declarations: they re-evaluate when an instance is created or a quantity changes. Summed values convert to numbers as in arithmetic, sotruecounts1andnullcounts0. See the root contract.
List and population extremes
Extremes keep the highest and lowest bids live as bids change
class Bid(bidder, amount):
this.bidder = bidder
this.amount = amount
high = Bid.max(bid -> bid.amount)
low = Bid.min(bid -> bid.amount)
assert(high, Number.NEGATIVE_INFINITY)
assert(low, Number.POSITIVE_INFINITY)
ada = Bid("ada", 120)
Bid("bo", 90)
assert(high, 120)
assert(low, 90)
ada.amount = 60
Bid("cy", 150)
assert(high, 150)
assert(low, 60)
- NUC 69 adds
max(),min()and their selector forms to lists and class instance lists.Bid.max(bid -> bid.amount)is the largest amount over every instance, compared exactly asMath.maxcompares, and before the first bidhighis-InfinityandlowisInfinity, the values ofMath.max()andMath.min(). highandloware live declarations: they re-evaluate when an instance is created or an amount changes. Compared values convert to numbers as in arithmetic, so the result is always a number. See the root contract.
List and population distinct values
Distinct values keep the regions of orders live as orders change
class Order(customer, region):
this.customer = customer
this.region = region
regions = Order.distinct(order -> order.region)
buyers = Order.distinct(order -> order.customer).length
assert(regions, [])
first = Order("ada", "north")
Order("bo", "south")
Order("ada", "north")
assert(regions, ["north", "south"])
assert(buyers, 2)
first.region = "east"
Order("cy", "south")
assert(regions, ["east", "south", "north"])
assert(buyers, 3)
- NUC 71 adds
distinct()anddistinct(selector)to lists and class instance lists.Order.distinct(order -> order.region)lists each region once, in the order of the first order that has it, and an empty list or class gives[]. regionsandbuyersare live declarations: they re-evaluate when an order is created or its region changes. Values are compared with the deep equality ofincludesand never converted, so1and"1"stay apart. See the root contract.
Object entry loops
Entry loops read the keys and values of a record
class Item(shelf, name, qty):
this.shelf = shelf
this.name = name
this.qty = qty
def stock(shelf, table):
for name, qty of table: Item(shelf, name, qty)
return Item.length
assert([stock("pantry", {rice: 4, oil: 2, salt: 1}), stock("fridge", {milk: 1, eggs: 12})], [3, 5])
assert(Item.map(item -> item.shelf + ":" + item.name + item.qty).join(" "), "pantry:rice4 pantry:oil2 pantry:salt1 fridge:milk1 fridge:eggs12")
- NUC 72 adds
for KEY, VALUE of SOURCE:, also spelled within. It visits an object's own entries in insertion order, binds each key and its value, and runs the body once per entry, as a single-name loop runs once per item. stocktakes any table: the pantry and fridge tables have different keys, and the loop reads each one without naming them. A rolled-backtryor asupposeblock leaves every object's entries where they were, in the same order. Any other source raisesTypeError("<source> is not an object"). See the root contract.
While loops
While loops step a world model until a goal holds
class Tank(level):
this.level = level
tank = Tank(2)
full = tank.level >= 10
hours = 0
while not full:
tank.level = tank.level + 3
hours = hours + 1
assert(tank.level, 11)
assert(hours, 3)
assert(full, true)
- NUC 63 adds
while CONDITION:with an indented or same-line body. The condition is tested with the truthiness ofifbefore every iteration, and each iteration sees the live values that its own changes caused, such asfullhere. - A loop runs once, imperatively, like
for: it leaves no standing rule and does not run again whentank.levelchanges later. A runaway loop stops after 100,000 iterations withTypeError("Loop did not terminate")and rolls back.whilestays an ordinary name everywhere else. See the root contract.
Destructuring
Destructuring declares one live name per field or position
size = {width: 3, height: 2}
{width, height} = size
area = width * height
corner = [4, 1]
x, y = corner
size.width = 5
corner = [0, 7]
assert: [width, height, area], [5, 2, 10]
assert: [x, y], [0, 7]
- NUC 67 adds destructuring declarations: object patterns
such as
{width, height} = size, renamed targets such as{width: wide} = size, and Python-style unpacking such asx, y = corner. - Each name is an ordinary declaration of its own,
width = size.widthandx = corner[0], so every name stays live: changingsizeorcornerupdates it. See the root contract.
Predicate counts
Predicate counts keep the number of open tickets live as tickets change
class Ticket(open): this.open = open
pending = Ticket.count(ticket -> ticket.open)
first = Ticket(true)
second = Ticket(false)
assert: pending, 1
second.open = true
assert: pending, 2
first.open = false
assert: pending, 1
- NUC 73 adds
count(predicate)to lists and class populations. It returnsfilter(predicate).lengthwithout allocating the filtered result, and calls the predicate once per item in receiver order. - Counts remain live in declarations and class-level rules. A valid empty
receiver gives
0; a missing or non-function predicate raisesTypeError("count expects a function"). The acceptedfilterspelling remains unchanged. See the root contract.
Final rest parameters
Final rest parameters collect positional extras without changing fixed defaults
def collect(head = 1, ...tail) => [head, tail]
assert(collect(), [1, []])
assert(collect(2, 3, 4), [2, [3, 4]])
assert(collect(5, [6, 7]), [5, [[6, 7]]])
- A final
...namein a parenthesized user signature receives a fresh list, including[]when there are no extras. Functions, methods and constructors share binding; a constructor label may fill a fixed slot, not its rest slot. No bare rest form or call-site spread is introduced. See NUC 74 and the root contract.
List and population modes
Modes keep the most requested size live as orders change
class Order(customer, size):
this.customer = customer
this.size = size
popular = Order.mode(order -> order.size)
assert(popular, null)
first = Order("ada", "M")
Order("bo", "L")
Order("cy", "L")
assert(popular, "L")
first.size = "S"
Order("di", "S")
Order("ed", "S")
assert(popular, "S")
- NUC 75 adds
mode()andmode(selector)to lists and class instance lists.Order.mode(order -> order.size)is the size that the most orders have; on a tie, the size that appears first wins, and an empty list or class gives undefined, stored asnull. popularis a live declaration: it re-evaluates when an order is created or its size changes. Items are matched with the deep equality ofincludesand never converted, asdistinctmatches them, so1and"1"are counted apart. See the root contract.
Noun list queries
Noun queries read like the model they describe
class Order(customer, amount):
this.customer = customer
this.amount = amount
revenue = sum of Order.map(order -> order.amount)
largest = max of Order.map(order -> order.amount)
regular = mode of Order.map(order -> order.customer)
Order("ada", 20)
second = Order("bo", 45)
Order("ada", 15)
assert: [revenue, largest, regular], [80, 45, "ada"]
second.amount = 70
Order("cy", 60)
assert: [revenue, largest, regular], [165, 70, "ada"]
amounts = [45, 20, 15]
amounts.sort()
assert: [amounts, min of amounts], [[15, 20, 45], 15]
- Revision 2 of NUC 75 adds
NOUN of OPERANDfor the list queries named by nouns:sum,max,minandmode.mode of listmeans exactlylist.mode(), and declarations that use it stay live the same way. - Actions keep the method call:
amounts.sort()sorts in place, whilemin of amountsreads a value. A selector stays a method argument, as inOrder.max(order -> order.amount), which equalsmax of Order.map(order -> order.amount). See the root contract.
List and population extreme items
Extreme items keep the leading and lowest bids live as bids change
class Bid(bidder, amount):
this.bidder = bidder
this.amount = amount
leader = Bid.maxBy(bid -> bid.amount)
lowest = Bid.minBy(bid -> bid.amount)
assert(leader, null)
assert(lowest, null)
ada = Bid("ada", 120)
Bid("bo", 90)
Bid("cy", 120)
Bid("di", 90)
assert(leader.bidder, "ada")
assert(lowest.bidder, "bo")
ada.amount = 60
Bid("ed", 150)
assert(leader.bidder, "ed")
assert(lowest.bidder, "ada")
- NUC 77 adds
maxBy(selector)andminBy(selector)to lists and class instance lists.Bid.maxBy(bid -> bid.amount)is the bid with the largest amount, the instance itself, soleader.biddernames the bidder. Before the first bidleaderandlowestarenull, and on a tie the earlier bid wins:cyanddido not displaceadaandbo. leaderandlowestare live declarations: they re-evaluate when a bid is created or an amount changes. Keys compare as>and<compare them, so numbers compare as numbers, strings as text and dates by time. See the root contract.
Extends clauses
Extends clauses declare subclasses as JavaScript and Java do
class Sensor(name, reading):
this.name = name
this.reading = reading
$Sensor.alarm = $Sensor.reading > 50
class Thermometer extends Sensor
class Barometer(name, reading, unit) extends Sensor:
this.name = name
this.reading = reading
this.unit = unit
kitchen = Thermometer("kitchen", 21)
roof = Barometer("roof", 1013, "hPa")
assert(kitchen.alarm, false)
assert(roof.alarm, true)
assert(roof.unit, "hPa")
kitchen.reading = 64
assert(kitchen.alarm, true)
assert(Sensor.length, 0)
- NUC 78 accepts
extendsin a class header as an optional spelling of the colon parent.class Thermometer extends Sensoris the bodyless subtype thatclass Thermometer: Sensorwith an indentedpassdeclares, andclass Barometer(name, reading, unit) extends Sensor:takes the indented body thatclass Barometer(name, reading, unit): Sensortakes. $Sensor.alarmapplies to both subtypes, which useSensor's constructor or their own, and each subtype keeps its own instance list.extendsstays an ordinary name everywhere else. See the root contract.
Property selector arguments
Selector arguments read properties without naming a parameter
class Order(customer, amount, paid):
this.customer = customer
this.amount = amount
this.paid = paid
revenue = Order.sum(.amount)
largest = Order.maxBy(.amount)
settled = Order.filter(.paid).map(.customer)
Order("ada", 20, true)
bo = Order("bo", 45, false)
assert: [revenue, largest.customer, settled], [65, "bo", ["ada"]]
bo.paid = true
Order("cy", 60, false)
assert: [revenue, largest.customer, settled], [125, "cy", ["ada", "bo"]]
- NUC 79 lets a call argument written
.amount, or a dotted path such as.address.city, stand for the functionorder -> order.amountthat reads it.Order.sum(.amount)totals every order, andOrder.filter(.paid).map(.customer)names the customers who have paid. - A selector stays live like the lambda it abbreviates: a new order or a
changed amount re-evaluates
revenueandlargest. It is written only as a whole call argument, sox = .amountstays a syntax error. See the root contract.
List and population averages
Averages keep mean temperatures live as readings change
class Room(name, temps):
this.name = name
this.temps = temps
$Room.mean = $Room.temps.average()
lab = Room("lab", [21, 23])
hall = Room("hall", [17, 18])
building = Room.average(room -> room.mean)
assert: [lab.mean, hall.mean, building], [22, 17.5, 19.75]
hall.temps.push(25)
Room("attic", [12])
assert: [hall.mean, building], [20, 18]
- NUC 80 adds
average()andaverage(selector)to lists and class instance lists.$Room.temps.average()is the mean of each room's readings, andRoom.average(room -> room.mean)the mean over every room: exactlysum(...)divided by the number of items. $Room.meanandbuildingare live declarations: a new reading or a new room re-evaluates them. An empty list or class averages to NaN, as0 / 0does. See the root contract.
Object spread entries
Spread entries keep derived listings in step with their products
class Product(name, price):
this.name = name
this.price = price
$Product.listing = {...$Product, currency: "USD"}
lamp = Product("lamp", 40)
draft = {...lamp.listing, price: lamp.price * 0.75}
assert: [lamp.listing.price, draft.price], [40, 30]
lamp.price = 60
lamp.stock = 3
assert: [lamp.listing, draft], [{id: "lamp", name: "lamp", price: 60, stock: 3, currency: "USD"}, {id: "lamp", name: "lamp", price: 45, stock: 3, currency: "USD"}]
- NUC 81 adds spread entries to object literals:
...SOURCEcopies the entries of the objectSOURCEholds, in order, and a later entry for the same key replaces its value.$Product.listingcopies each product and adds a currency, anddraftcopies the listing with a discounted price. - A spread stays live: a changed price and the new
stockentry reach both records. A class-level rule that spreads its own receiver leaves out the property it declares, solistingnever holds an older listing. See the root contract.
Depth-limited reasoning selections
Depth keeps an alarm's explanation to its direct causes
pressure = 120
limit = 100
temperature = 70
manual = false
strained = pressure > limit
hot = temperature > 90
alarm = [strained, hot, manual].includes(true)
causes = alarm |> why |> depth(1)
assert: causes.map(step -> step.node), ["alarm", "strained", "hot", "manual"]
assert: (why alarm).length, 7
pressure = 90
temperature = 95
assert: causes.map(step -> step.holds), [true, false, true, false]
- NUC 82 adds the reasoning stage
|> depth(LIMIT). It keeps the steps of a selection that lie withinLIMITsteps of where the walk that selected them began, in their order, soalarm |> why |> depth(1)is the alarm and the facts it reads directly: four steps, wherewhy alarmselects seven. - The selection stays live: new pressures and temperatures update the steps it keeps, and a limit read from a variable re-derives it when the variable changes. See the root contract.
Hypothetical differences
Diff lists what a warmer room would change in a heating plan
temperature = 18
target = 21
heating = temperature < target
fan = temperature > 30
cost = heating ? 4 : 0
suppose temperature = 24:
changes = model |> diff
assert: changes.map(step -> step.node), ["temperature", "heating", "cost"]
target = 26
assert: changes.map(step -> step.node), ["temperature", "target"]
assert: [heating, cost], [true, 4]
- NUC 83 adds the reasoning stage
|> diff. Inside asupposeblock it keeps the steps of a selection that the block added or changed, somodel |> diffanswers what a hypothetical would do without naming any node: warming the room to 24 turns the heating off and drops its cost, while the fan, which also reads the temperature, keeps its value. - The selection stays live inside the block: with the target raised to 26
the heating is back on, so only the temperature and the target still
differ. Outside a block the stage raises
TypeError("Cannot use 'diff' outside suppose"). See the root contract.
List and population medians
Medians keep typical delivery times live as orders arrive
class Order(city, minutes):
this.city = city
this.minutes = minutes
Order("oslo", 30)
Order("oslo", 25)
Order("bergen", 90)
late = Order("bergen", 105)
typical = Order.median(order -> order.minutes)
local = Order.filter(order -> order.city == "oslo").median(order -> order.minutes)
assert: [typical, local], [60, 27.5]
Order("oslo", 8)
late.minutes = 40
assert: [typical, local], [30, 25]
- NUC 84 adds
median()andmedian(selector)to lists and class instance lists.Order.median(order -> order.minutes)is the middle delivery time of every order, and with an even number of orders the mean of the two middle times. typicalandlocalare live declarations: a new order or a changed time re-evaluates them. Once the late order takes 40 minutes, the 90-minute order is the slowest, so however slow it is,typicalstays 30, while the mean of the five orders is 38.6. See the root contract.
Is comparisons
Is matches quoted and bare words as == does
status = "PENDING"
if status is SHIPPED:
stage = "done"
else:
stage = "open"
late = (status is not 'SHIPPED')
assert: [stage, late], ["open", true]
status = "SHIPPED"
assert: [stage, late], ["done", false]
SHIPPED = "DELIVERED"
assert: [stage, late], ["open", false]
- NUC 86 adds
isandis notas spellings of==and!=for numbers, strings, booleans, null and property reads. A quoted right operand is a string in either quote, and a lone bare word such asSHIPPEDreads the variable of that name, or its own text while nothing defines it. Defining, changing or deletingSHIPPEDre-evaluates every rule that compares with it, while the quoted'SHIPPED'stays text. isworks in conditions, parentheses, call arguments, lists and object values. Where a statement can follow, it stays an ordinary name, so writelate = (status is not 'SHIPPED')rather than leaving the comparison bare. See the root contract.
Initializing constructor parameters
Constructor parameters can assign the properties they name
class Room(this.name, this.temp, this.target = 21)
$Room.heating = $Room.temp < $Room.target
lab = Room("lab", 18)
hall = Room("hall", 23, 25)
assert: [lab.heating, hall.heating], [true, true]
lab.temp = 22
hall.target = 20
assert: [lab.heating, hall.heating], [false, false]
- NUC 87 lets a constructor parameter written
this.nameorself.namealso assign the property it names, soclass Room(this.name, this.temp, this.target = 21)declares whatclass Room(name, temp, target = 21):declares with one indentedthis.name = nameline per parameter. Types, literal defaults and labelled arguments work as before. - The assignments run before the constructor's own statements, and the
properties they make are ordinary:
$Room.heatingfollows a changed temperature or target. Parameters without the prefix still create no properties. See the root contract.
Derivation path selections
Path shows how a discount tier reaches an order total
subtotal = 120
tier = "gold"
rate = tier == "gold" ? 20 : 5
discount = subtotal * rate / 100
shipping = 9
total = subtotal - discount + shipping
how = total |> why |> path(tier)
assert: how.map(step -> step.node), ["total", "discount", "rate", "tier"]
assert: (why total).length, 6
tier = "silver"
assert: how.map(step -> step.holds), [123, 6, 5, "silver"]
- NUC 88 adds the reasoning stage
|> path(TARGET). It keeps the steps of a selection that lie on a dependency path between the walk andTARGET, in their order, sototal |> why |> path(tier)is how the tier reaches the total: through the discount and its rate, four steps wherewhy totalselects six, leaving out the subtotal and the shipping. - The selection stays live: once the tier is silver, the same four steps hold
the new rate, discount and total, and a rule rewired to read the tier would
join it. After
affects,|> path(TARGET)keeps what a change moves on its way toTARGET. See the root contract.
Named function declarations
Function declarations keep JavaScript-style functions live
rate = 5
function shipping(weight) { return rate * weight }
function total(price, weight) {
return price + shipping(weight)
}
order = total(40, 2)
assert(order, 50)
rate = 4
assert(order, 48)
function shipping(weight) { return rate * weight + 1 }
assert(order, 49)
- NUC 89 accepts the named function declaration of
JavaScript, TypeScript and PHP.
function total(price, weight) { ... }declares exactly the function thatdef total(price, weight):declares with the same statements, written in braces instead of an indented body. orderstays live through both functions: a new rate updates it, and so does redeclaringshipping, whichever spelling either declaration uses. Declarations are not hoisted, and in an expressionfunctionstill takes only an anonymous literal. See the root contract.
Enum declarations
Enums name a model's categories once
enum Stage: TODO, DOING, DONE
class Task(title, stage):
this.title = title
this.stage = stage
$Task.active = $Task.stage == Stage.DOING
write = Task("write", Stage.TODO)
review = Task("review", Stage.DOING)
assert([write.active, review.active], [false, true])
write.stage = Stage.DOING
assert(Task.count(t -> t.active), 2)
- NUC 90 adds enum declarations.
enum Stage: TODO, DOING, DONEdeclaresStageas an object whose members hold their own names, soStage.DOINGis"DOING". A member may instead take a literal value, as inenum Level: LOW = 1, HIGH = 3, andenum Stage:followed by an indented block lists one member per line. - Rules that read a member stay live like any other: moving
writetoStage.DOINGmakes it active, and the count follows. The enum itself is read-only, soStage.DONE = "X"raisesTypeError("Enums are read-only"). See the root contract.
List comprehensions
List comprehensions keep Python-style lists live
class Item(name, price):
this.name = name
this.price = price
budget = 10
cheap = [item.name for item in Item if item.price <= budget]
Item("pen", 3)
ink = Item("ink", 12)
assert(cheap, ["pen"])
budget = 15
assert(cheap, ["pen", "ink"])
ink.price = 20
assert(cheap, ["pen"])
- NUC 92 accepts Python's list comprehensions.
[item.name for item in Item if item.price <= budget]is exactlyItem.filter(item => item.price <= budget).map(item => item.name), andfor item of Itemis the same asfor item in Item. cheapstays live like the arrow spelling: a new budget or a changed price updates it. A comprehension has oneforand at most oneif, and its lambdas read variables and their own name but not the parameters of an enclosing function. See the root contract.
Implicit receiver properties
A leading dot reads a property of the assigned object
class Box(w, h):
this.w = w
this.h = h
$Box.area = .w * .h
box = Box(2, 3)
box.label = `${.w}x${.h}`
assert([box.area, box.label], [6, "2x3"])
box.w = 5
box.h = 4
assert([box.area, box.label], [20, "5x4"])
- NUC 102 reads
.win the value of an assignment to a property as a property of the same object, its receiver:$Box.area = .w * .his$Box.area = $Box.w * $Box.h, andbox.label = `${.w}x${.h}`readsbox.wandbox.h. - The parser writes the path out, so the rule renders, depends, stays live
and rolls back exactly as its spelled-out form. A call argument that starts
with
.stays a selector, and a leading dot anywhere without a property target keeps its error. See the root contract.
Any and all class references
Any and all state a class condition and the rule it guards
class Object(number):
this.number = number
every Object.label is square
if any Object.number > 4:
all Object.color is red
a = Object(3)
b = Object(7)
assert([a.label, b.label], ["square", "square"])
assert([a.color, b.color], [null, "red"])
- NUC 104 reads
any Objectandall Objectas the class reference$Object, wherever NUC 98 readsevery Objectas one and inside if statements, where NUC 98 rejectsevery Object. Soif any Object.number > 4:is the class-level conditionalif $Object.number > 4:, andall Object.color is redis the rule$Object.color is redit guards for each Object over 4. - They are spellings, not quantifiers: each instance is tested on its own,
so only
bturns red.any n in xs: n > 4andall n in xs: n > 4stay the quantifiers of NUC 62, and variables namedallandanywork as before. See the root contract.
List and population sorting by key
Sorting by key keeps a live agenda while the list keeps its order
tasks = [{name: "ship", due: 3}, {name: "plan", due: 1}, {name: "build", due: 2}]
agenda = tasks.sortBy(task -> task.due)
assert(agenda.map(task -> task.name), ["plan", "build", "ship"])
tasks.push({name: "test", due: 2})
assert(agenda.map(task -> task.name), ["plan", "build", "test", "ship"])
tasks[2].due = 4
assert(agenda.map(task -> task.name), ["plan", "test", "ship", "build"])
assert(tasks.map(task -> task.name), ["ship", "plan", "build", "test"])
- NUC 105 adds
sortBy(selector)to lists and class populations.tasks.sortBy(task -> task.due)is a new list of the tasks themselves in ascending order of their due days, and tasks due the same day keep their list order, sotestfollowsbuilduntilbuildmoves to day 4. agendais a live declaration that follows new tasks and changed days, whiletaskskeeps its own order, wheresortwould reordertasksitself. Keys compare as<compares them, so numbers compare as numbers and strings as text. See the root contract.
Intersect and except reasoning selections
Intersect and except tell apart what two symptoms rest on
fan = 2
load = 40
voltage = 230
current = load / voltage * 100
heat = current * 3 + fan
noise = fan * 10
shared = why heat |> intersect(why noise)
own = why heat |> except(why noise)
assert(shared.map(step -> step.node), ["fan"])
assert(own.map(step -> step.node), ["heat", "current", "load", "voltage"])
noise = fan * 10 + load
assert(shared.map(step -> step.node), ["fan", "load"])
assert(own.map(step -> step.node), ["heat", "current", "voltage"])
- NUC 106 adds the reasoning stages
|> intersect(OTHER)and|> except(OTHER).why heat |> intersect(why noise)keeps the steps of the heat's explanation whose node the noise's explanation also selects, here the fan, andwhy heat |> except(why noise)keeps the others: what only the heat rests on. - Both keep the first selection's order and every field of the steps they keep, and they stay live: once the noise also reads the load, the load moves from the heat's own causes to the shared ones. See the root contract.
Python-style self parameters
Methods may declare self as Python methods do
class Account:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance = self.balance + amount
return self.balance
account = Account(100)
assert(account.deposit(5), 105)
assert(account.balance, 105)
- NUC 107 lets a method in a class's indented body
declare its receiver as a leading
selfparameter, as Python does.def deposit(self, amount):declares exactlydef deposit(amount):, and the callaccount.deposit(5)passes no receiver. def __init__(self, balance):declares the class'sinitconstructor, exactlydef init(balance):, soAccount(100)runs it. The bodies read the receiver throughself, as every method does. See the root contract.
List and population partitions
Partition keeps shipped and pending orders apart in one live rule
class Order(total, shipped):
this.total = total
this.shipped = shipped
totals = Order.partition(order -> order.shipped).map(side -> side.map(order -> order.total))
Order(40, true)
late = Order(15, false)
Order(90, true)
assert(totals, [[40, 90], [15]])
late.shipped = true
Order(25, false)
assert(totals, [[40, 15, 90], [25]])
- NUC 108 adds
partition(predicate)to lists and class populations.Order.partition(order -> order.shipped)is a list of two lists: the orders the predicate keeps, asfilterkeeps them, and the orders it drops, each side in population order. - The rule is stated once and runs once per order, where two
filtercalls state it twice, the second time negated.totalsstays live: the late order joins the shipped side once it ships, and a new pending order takes its place on the other. See the root contract.
Operator section arguments
Operator sections pass a comparison without naming a parameter
cells = [0, 3, 0, 7, 7]
filled = cells.filter(!= 0)
sevens = cells.count(== 7)
assert([filled, sevens], [[3, 7, 7], 2])
cells.push(7)
assert([filled, sevens], [[3, 7, 7, 7], 3])
- NUC 109 lets a call argument that begins with a
binary operator stand for the function that applies the operator to its
argument:
cells.filter(!= 0)iscells.filter(cell -> cell != 0), andcells.count(== 7)counts the sevens. - The rest of the argument is read as if the item stood before the
operator, with the usual precedence, so
xs.map(* 2 + 1)mapsx -> x * 2 + 1. Both declarations stay live like their lambdas: another seven extendsfilledand raisessevens. See the root contract.
Python string method aliases
Python string methods classify files and list them
class File(name):
this.name = name
$File.table = $File.name.endswith(".csv")
report = File("report.csv")
notes = File("notes.txt")
tables = ", ".join(File.filter(file -> file.table).map(file -> file.name))
assert([report.table, notes.table, tables], [true, false, "report.csv"])
notes.name = "notes.csv"
assert(tables, "report.csv, notes.csv")
- NUC 110 adds Python's names for three string methods:
name.endswith(".csv")isname.endsWith(".csv"),name.startswith("draft_")isname.startsWith("draft_"), and", ".join(names), with the separator as the receiver, isnames.join(", "). jointakes a list or a class's instances, so", ".join(File)joins the files asFile.join(", ")does. The class-level rule and the list stay live: renaming the notes to a CSV file makes it a table and adds it totables. See the root contract.
Reactive string padding
Padding keeps a price list aligned as it changes
item = "tea"
price = "4"
line = item.padEnd(8, ".") + price.padStart(3)
assert(line, "tea..... 4")
item = "honey"
price = "12"
assert(line, "honey... 12")
- NUC 111 adds JavaScript's
padStartandpadEndto strings:price.padStart(3)puts spaces before the price until it holds three characters, anditem.padEnd(8, ".")puts dots after the item until it holds eight. A fill of several characters is cut to the gap, and text that already holds the length is returned as it is. linestays live like itsrepeatspelling,item + ".".repeat(8 - item.length), so a new item and price realign it. See the root contract.
Node names of reasoning selections
Nodes names the facts a heater rests on and what insulation moves
outside = 4
target = 21
insulation = 0.8
loss = (target - outside) * insulation
heater = loss * 2
causes = heater |> why |> stated |> nodes
moved = insulation |> affects |> nodes
assert(causes, ["target", "outside", "insulation"])
assert(moved, ["loss", "heater"])
solar = 5
heater = loss * 2 - solar
assert(causes, ["solar", "target", "outside", "insulation"])
- NUC 112 adds the final reasoning stage
|> nodes, which names the nodes of a selection's steps in their order.heater |> why |> stated |> nodesnames the facts the heater rests on, andinsulation |> affects |> nodeswhat a change of the insulation reaches. - Both lists are the names that
(heater |> why |> stated).map(step => step.node)and(insulation |> affects).map(step => step.node)give, and they stay live the same way: once the heater also accounts for the solar gain,solarjoins the facts it rests on. See the root contract.
List and population products
Products keep the chance that a trip connects live as flights change
class Flight(code, onTime):
this.code = code
this.onTime = onTime
first = Flight("AB1", 0.5)
Flight("CD2", 0.75)
trip = Flight.product(flight -> flight.onTime)
assert(trip, 0.375)
first.onTime = 0.75
Flight("EF3", 0.5)
assert(trip, 0.28125)
- NUC 114 adds
productto lists and class populations, the multiplicative sibling ofsum.Flight.product(flight -> flight.onTime)multiplies the chances that the flights are on time, sotripis the chance that all of them are, when the flights are independent. tripstays live like itsreducespelling,Flight.reduce((total, flight) => total * flight.onTime, 1): a likelier first flight and a third connection both update it. Without a selector,sides.product()multiplies the items themselves, and an empty list or class gives1. See the root contract.
Repeat loops
Repeat loops advance a world model a counted number of steps
class Cup(temp):
this.temp = temp
tea = Cup(90)
room = 20
cool = tea.temp < 40
minutes = 3
repeat minutes:
tea.temp = tea.temp - (tea.temp - room) / 2
assert(tea.temp, 28.75)
assert(cool, true)
- NUC 115 adds
repeat COUNT:with an indented or same-line body, the count-controlled sibling ofwhile. The count is read once, before the first iteration, and each iteration's changes, with what they propagate to standing rules such ascool, are live before the next iteration runs. - Each minute the tea loses half of its difference from the room, so three
minutes take it from
90to28.75. The loop runs once, imperatively: it leaves no standing rule and does not run again whenminuteschanges later. A fraction truncates, a count of zero or less runs nothing, and a count of more than 100,000 iterations raisesTypeError("Repeat count is too large")before the first one.repeatstays an ordinary name everywhere else, and"ab".repeat(2)is still"abab". See the root contract.
Size and emptiness aliases
Size and emptiness methods keep an order queue's rules live
orders = ["tea"]
idle = orders.isEmpty()
backlog = orders.size()
orders.push("cake", "pie")
assert([idle, backlog], [false, 3])
orders.pop()
orders.pop()
orders.pop()
assert([idle, backlog, orders.length], [true, 0, 0])
- NUC 116 adds the size and emptiness methods that
Java, Kotlin, C++ and Rust write, as aliases of
lengthon lists, class populations and strings:size()andlen()arelength,isEmpty()andis_empty()arelength == 0, andisNotEmpty()islength > 0. Strings also take Java'slength(), as lists and populations do. idleandbacklogare standing rules, so every push and pop of the queue updates them, asorders.length == 0andorders.lengthwould. Reads without a call, such asorders.size, stay undefined, and other values keep their errors. See the root contract.
First and last element methods
First and last methods keep a sensor's newest reading live
class Sensor(name):
this.name = name
this.readings = []
$Sensor.newest = $Sensor.readings.last()
$Sensor.firstAlarm = $Sensor.readings.first(reading -> reading > 40)
oven = Sensor("oven")
oven.readings.push(35, 52, 38)
assert([oven.newest, oven.firstAlarm], [38, 52])
oven.readings.push(41)
assert([oven.newest, oven.firstAlarm], [41, 52])
oven.readings.shift()
oven.readings.shift()
assert([oven.newest, oven.firstAlarm], [41, 41])
- NUC 117 adds the
firstandlastmethods that Kotlin, Rust, Swift, Ruby and C#'s LINQ write, as aliases on lists and class populations:first()isat(0)andlast()isat(-1), and with a predicate, as Kotlin writesorders.first { it.open },first(test)isfind(test)andlast(test)isfindLast(test). - Each sensor's
newestandfirstAlarmfollow its own readings through the class-level rules, as$Sensor.readings.at(-1)and$Sensor.readings.find(reading -> reading > 40)would: a new reading replaces the newest, and shifting out the old ones moves the first alarm to41. An empty list gives undefined and a predicate that accepts nothingnull, as their spellings do. See the root contract.
Case conversion method aliases
Case conversion methods keep a sensor's labels normalized
class Sensor(label):
this.label = label
$Sensor.key = $Sensor.label.to_lowercase()
$Sensor.banner = $Sensor.label.uppercased()
door = Sensor("Front Door")
assert([door.key, door.banner], ["front door", "FRONT DOOR"])
door.label = "Side Door"
assert([door.key, door.banner], ["side door", "SIDE DOOR"])
- NUC 118 adds the case conversion methods that
Kotlin, Rust and Swift write, as aliases of
toUpperCase()andtoLowerCase()on strings: Kotlin'suppercase()andlowercase(), Rust'sto_uppercase()andto_lowercase(), and Swift'suppercased()andlowercased(). - Each sensor's
keyandbannerfollow its own label through the class-level rules, as$Sensor.label.toLowerCase()and$Sensor.label.toUpperCase()would. The mapping is the full Unicode one of those spellings, so"Straรe".uppercase()is"STRASSE", and other values keep their errors. See the root contract.
Finally clauses
Finally clauses record every attempt to unlock a door
train_attempts = []
def unlock(code):
try:
if code != 1234:
throw "WRONG CODE"
return "unlocked"
catch reason:
return reason
finally:
train_attempts.push(code)
assert(unlock(1111), "WRONG CODE")
assert(unlock(1234), "unlocked")
assert(train_attempts, [1111, 1234])
- NUC 119 adds the
finallyclause of Python, JavaScript, Java, Kotlin and C# to completetry/catchstatements:finally:and a suite, on the line after the catch suite, run however the statement ends. unlockreturns from its body and from its catch suite, and thefinallysuite records the attempt on both paths before the value is returned. A failed body is rolled back before the catch suite runs, as without the clause, and areturnin thefinallysuite would replace the pending result. See the root contract.
Union reasoning selections
Union lists every fact behind either of two alarms
pressure = 5
flow = 3
temperature = 70
strain = pressure * flow
leak = flow > 2 && pressure > 4
overheat = temperature + strain > 80
inspect = why leak |> union(why overheat) |> stated
assert(inspect.map(step -> step.node), ["flow", "pressure", "temperature"])
valve = 1
leak = flow > 2 && pressure > 4 && valve == 1
assert(inspect.map(step -> step.node), ["flow", "pressure", "valve", "temperature"])
- NUC 120 adds the reasoning stage
|> union(OTHER).why leak |> union(why overheat)keeps the steps of the leak's explanation and adds the steps of the overheat's explanation that it does not hold yet, so every node that either alarm rests on appears once: the flow and the pressure behind both alarms are listed with the leak's. - The union is still a selection, so
|> statednarrows it to the facts to inspect, and it stays live: once the leak rule also checks the valve, the valve joins them. See the root contract.
Held values of reasoning selections
Holds lists the readings behind a frost warning and what the wind moves
air = 3
ground = -1
wind = 12
chill = air - wind / 4
frost = chill + ground < 1
readings = frost |> why |> stated |> holds
moved = wind |> affects |> holds
assert(readings, [-1, 3, 12])
assert(moved, [0, true])
wind = 4
assert([readings, moved], [[-1, 3, 4], [2, false]])
- NUC 121 adds the final reasoning stage
|> holds, which gives the values of a selection's steps in their order.frost |> why |> stated |> holdslists the readings the frost warning rests on, andwind |> affects |> holdsthe values that a change of the wind reaches: the chill and the warning itself. - Both lists are the values that
(frost |> why |> stated).map(step => step.holds)and(wind |> affects).map(step => step.holds)give, and they stay live the same way: once the wind drops, the readings show its new speed and the warning clears. See the root contract.
Python-style except clauses
Except clauses fall back to another sensor when a reading fails
hall = 19
try:
kitchen = cellar + 1
except Exception as fault:
kitchen = hall - 1
note = fault
heating = kitchen < 20
assert([kitchen, note, heating], [18, ReferenceError("cellar is not defined"), true])
hall = 22
assert([kitchen, heating], [21, false])
- NUC 122 reads Python's catch-all clause headers:
except:andexcept Exception:arecatch:, andexcept Exception as fault:iscatch fault:, with the same suite, the same rollback of the failed body and the same binding. - The kitchen's reading derives from a cellar sensor that has not reported, so reading it fails, and the clause estimates the kitchen from the hall instead and records why. The estimate is a declaration like any other, so it follows the hall's reading, and the heating follows the estimate. See the root contract.
List and population variances and standard deviations
Standard deviations keep the scatter of delivery times live as orders change
class Delivery(minutes):
this.minutes = minutes
Delivery(30)
Delivery(25)
late = Delivery(35)
scatter = Delivery.stdev(delivery -> delivery.minutes)
assert(scatter, 4.08248290463863)
late.minutes = 90
Delivery(40)
assert(scatter, 25.829972899714782)
- NUC 123 adds
variance()andstdev(), with and without a selector, to lists and class instance lists.Delivery.stdev(delivery -> delivery.minutes)is the population standard deviation of the delivery times: the square root of their mean squared distance from their mean. scatteris a live declaration, so a slower delivery and a new order both update it. The distances are taken from the mean, which keeps the spread of large values where the mean of the squares minus the square of the mean cancels it, andvariance()gives the square of the same spread. See the root contract.
List and population quantiles
The ninetieth percentile keeps the slow tail of response times live
class Request(millis):
this.millis = millis
Request(120)
Request(80)
spike = Request(300)
Request(95)
Request(110)
Request(140)
p90 = Request.quantile(0.9, request -> request.millis)
assert(p90, 220)
spike.millis = 100
Request(150)
assert(p90, 144)
- NUC 124 adds
quantile(q)andquantile(q, selector)to lists and class instance lists.Request.quantile(0.9, request -> request.millis)is the time that nine in ten requests stay within: the rank0.9lies halfway between the fifth and the sixth of the six sorted times, so the result interpolates between them, as NumPy's and pandas'quantiledo. p90is a live declaration. Once the spike settles at 100 ms the slow tail shrinks, and a new 150 ms request moves the rank between the sixth and the seventh sorted time, which gives0.6 * 140 + 0.4 * 150. See the root contract.
Stepped slices
Stepped slices deal the chores round-robin as roommates move in
chores = ["dishes", "laundry", "trash", "floors", "plants", "mail"]
class Roommate(turn):
this.turn = turn
$Roommate.duties = chores[$Roommate.turn::Roommate.length]
ana = Roommate(0)
ben = Roommate(1)
assert([ana.duties, ben.duties], [["dishes", "trash", "plants"], ["laundry", "floors", "mail"]])
cy = Roommate(2)
chores.push("cooking")
assert([ana.duties, cy.duties], [["dishes", "floors", "cooking"], ["trash", "mail"]])
- NUC 125 adds a step to slices:
SEQUENCE[start:stop:step]takes every step-th item from the start, and a negative step walks backward, as Python's slices do.chores[$Roommate.turn::Roommate.length]starts at each roommate's turn and steps by the number of roommates, which deals the chores round-robin. dutiesis a class-level rule, so every roommate keeps a share of its own. When Cy moves in, the step grows to 3 and every share is dealt again, and the new chore joins the share whose turn it falls on. See the root contract.
Repeat-until loops
Repeat-until loops move a lift to the next call
class Lift(floor):
this.floor = floor
lift = Lift(1)
calls = [1, 4, 6]
stopped = calls.includes(lift.floor)
repeat: lift.floor += 1
until stopped
assert(lift.floor, 4)
calls.push(2)
assert([lift.floor, stopped], [4, true])
- NUC 126 adds
repeat:with an indented or same-line body, followed byuntil CONDITIONon its own line after the body: the exit-controlled sibling ofwhile. The body runs first, and the condition is tested after every iteration with the truthiness ofif, so the body always runs at least once. - The lift waits at a call on floor 1, so
stoppedalready holds, yet the loop moves it on: one floor at a time, untilstopped, a standing rule that follows every move, holds again at floor 4. Awhile not stopped:loop would not move it at all. The loop runs once, imperatively: it leaves no standing rule and does not run again when a new call arrives. A loop still unfinished after 100,000 iterations raisesTypeError("Loop did not terminate")and rolls back, andrepeatanduntilstay ordinary names everywhere else. See the root contract.
Origins and outcomes of reasoning selections
Origins and outcomes show where a change of pressure enters and which alarms it ends at
pressure = 5
flow = 3
temperature = 70
strain = pressure * flow
leak = flow > 2 && pressure > 4
overheat = temperature + strain > 80
shutdown = pressure > 9 || overheat
enters = pressure |> affects |> origins
alarms = pressure |> affects |> outcomes
assert(enters.map(step -> step.node), ["strain", "leak"])
assert(alarms.map(step -> step.node), ["leak", "shutdown"])
leak = flow > 2 && strain > 12
panel = [leak, shutdown]
assert([enters.map(step -> step.node), alarms.map(step -> step.node)], [["strain"], ["panel"]])
- NUC 128 adds the reasoning stages
|> originsand|> outcomes, which keep the two ends of a selection.pressure |> affects |> originskeeps where a change of the pressure enters the model: the strain and the leak check, which read it and rest on nothing else it moves. The shutdown reads the pressure too, but it also rests on the overheat, which the pressure moves through the strain. pressure |> affects |> outcomeskeeps where the change ends: the leak check and the shutdown, which nothing reads. Both stay live: once the leak check reads the strain, the change enters at the strain alone, and once a panel shows both alarms, it ends at the panel. See the root contract.
List and population zipping
Zip weighs every grade by its credits for a live grade point average
grades = [4, 4, 3]
credits = [3, 2, 3]
gpa = grades.zip(credits, (grade, credit) -> grade * credit).sum() / credits.sum()
assert(gpa, 3.625)
grades.push(2)
credits.push(4)
assert(gpa, 3.0833333333333335)
- NUC 129 adds
zip(other)andzip(other, combine)to lists and class instance lists.grades.zip(credits, ...)pairs each grade with the credits at the same position and weighs it with the combiner, as Python'szip, Kotlin'szipwith a transform and lodash'szipWithpair parallel sequences. gpais a live declaration, so a new course and its credits update it. The two top grades carry different credits, which a spelling that finds positions withindexOfwould confuse, andzipstops at the shorter sequence, so a grade waiting for its credits counts once they arrive. See the root contract.
Reversal method aliases
Reversal methods keep an undo history newest first
edits = ["draft", "trim intro"]
undo = edits.reversed()
top = edits.toReversed()[0]
assert([undo, top], [["trim intro", "draft"], "trim intro"])
edits.push("fix typo")
assert([undo, top, edits.length], [["fix typo", "trim intro", "draft"], "fix typo", 3])
- NUC 131 adds
reversed(), as Kotlin and Swift write it, andtoReversed(), as JavaScript writes it, to lists and class instance lists, andreversed()andreverse(), as Kotlin and Ruby write them, to strings. On a list they are exactly the acceptedreverse(), which returns a new list and leaves its receiver unchanged, and on a string exactlytext[::-1], which reverses its characters. undoandtopare live declarations over the history, so the newest edit comes first after every push, whileeditskeeps the order the edits were made in. See the root contract.
Edge lists of reasoning selections
Edges draws the wiring behind a heat alarm
temp = 31
humidity = 70
heat = temp > 30
damp = humidity > 60
alarm = heat && damp
wiring = (alarm |> why |> edges).map(edge -> edge.join(" -> "))
assert(wiring, ["heat -> alarm", "damp -> alarm", "temp -> heat", "humidity -> damp"])
wind = 4
alarm = heat && damp && wind < 10
assert(wiring, ["heat -> alarm", "damp -> alarm", "wind -> alarm", "temp -> heat", "humidity -> damp"])
- NUC 133 adds the final reasoning stage
|> edges, which lists the dependency edges of a selection's steps: for each step, in the selection's order, one[input, node]pair for every input the step reads.alarm |> why |> edgesgives the edges of the alarm's explanation, and mapping each pair to an arrow draws it. - The pairs are the ones the steps'
fromlists record, and they stay live the way the explanation does: once the alarm also reads the wind, the wind's edge joins the wiring. See the root contract.
Input counts of reasoning selections
- NUC 145 adds the final stage
selection |> indegrees, exactly(selection).map(step -> step.from.length)for that graph selection.alarm |> why |> indegreesreports how many recorded inputs each explanation step has, in its order; an alarm with two direct inputs starts with2, and one that also reads wind starts with3. - Counts include inputs outside the selection, stay reactive through
equal-valued rewiring, give
0for zero-input steps and[]for an empty selection. The stage keeps the same source coercion, observer exclusion, shadowing and final-projection boundaries asnodes,holdsandedges. See the root contract and its two executed, behavior-equivalent specification/reference cases.
Reactive list flattening
Flat turns nested lists into one live list
weeks = [["mon", "tue"], ["wed"]]
days = weeks.flat()
assert(days, ["mon", "tue", "wed"])
weeks.push(["thu", "fri"])
assert(days, ["mon", "tue", "wed", "thu", "fri"])
- NUC 103 adds JavaScript's
flatto lists and class populations:weeks.flat()is exactlyweeks.flatMap(v => v), andweeks.flat(2)flattens two levels, as two such steps do.flat(0)copies, andflat(Number.POSITIVE_INFINITY)flattens every level. daysstays live like itsflatMapspelling, so another week of days extends it. See the root contract.
Membership tests
Membership tests read in the order they are said
allowed = ["new", "paid"]
status = "paid"
open = status in allowed
closed = status not in allowed
assert([open, closed], [true, false])
allowed = ["new"]
assert([open, closed], [false, true])
- NUC 97 adds
item in collectionanditem not in collection, the shorter spellings ofcollection.includes(item)and!collection.includes(item)for lists, classes and strings. Both stay live, so changingallowedre-evaluatesopenandclosed. - A declaration over a null collection holds
nulluntil the collection is set, and any other value, such as a number or an object, raisesTypeError("<collection> is not a collection").inkeeps itsfor, comprehension and quantifier readings. See the root contract.
Every and predicate sentences
Every states a class-level claim as it is said
class Human(name: str):
this.name = name
every Human is mortal
every Human.legs is 2
socrates = Human("Socrates")
assert([socrates.mortal, socrates.legs], [true, 2])
assert(every h in Human: h.mortal, true)
- NUC 98 reads
every Humanas the class reference$Human, soevery Human.legs is 2is the class-level rule$Human.legs = 2, andevery h in Human: h.mortalas the quantifierall h in Human: h.mortal. - Inside an if statement
every HumanraisesSyntaxError("Use all instead of every inside if")before the program runs, so a condition readsif any Human.age > 60:and the rule it guardsall Human.senior = true. - The statement
every Human is mortal, like$Human is mortal, states$Human.mortal = truefor every instance, andwhyreports it as that rule. Elsewhereeverystays an ordinary name, soxs.every(...)and a variable namedeverywork as before. See the root contract.
Colon-free implicit iterator suites
Named iterator suites use indentation without a colon
class Parcel(weight):
this.weight = weight
light = Parcel(4)
heavy = Parcel(7)
total = 0
for Parcel
total += it.weight
assert(total, 11)
for Parceluses the same one-shot population snapshot, localitand imperative suite asfor Parcel:. The optional colon never replaces the accepted spelling or broadens the source expression.- See NUC 127 and the root contract.
Rust string boundary method aliases
Rust boundary methods keep file flags live
class File(name):
this.name = name
$File.draft = $File.name.starts_with("draft_")
$File.table = $File.name.ends_with(".csv")
file = File("draft_report.csv")
assert([file.draft, file.table], [true, true])
file.name = "notes.txt"
assert([file.draft, file.table], [false, false])
[file.draft, file.table]
# return: [false,false]
- NUC 132 adds Rust's familiar
starts_withandends_withnames for the accepted string boundary queries. Each file's flags follow its name through the same class-rule dependencies. - The first argument converts to Nucleoid text; missing arguments test
"undefined"and further arguments are evaluated and ignored. Rust's pattern traits and static typing are not introduced. All accepted JavaScript and Python spellings remain available. - See the root contract.
Unknown constructor arguments as properties
Unknown constructor arguments become live properties
class Product(name):
this.name = name
$Product.total = $Product.price * $Product.quantity
item = Product(name="pen", price=2, quantity=3)
assert(item, {"id": "item", "name": "pen", "price": 2, "quantity": 3, "total": 6})
item.quantity = 5
assert(item.total, 10)
item.total
# return: 10
- NUC 136 turns a constructor label that names no
parameter into a property: the call acts as if the constructor declared
the name and assigned
this.<name> = <name>after its own statements. The class declares only what its constructor uses, and the class-level rule readspriceandquantitylike any other property. - Positional calls, declared labels and the binding errors for repeated labels are unchanged. See the root contract.
Integer range literals
Ranges keep a shift's hours in step with its bounds
open = 9
close = 13
hours = open..<close
assert(hours, [9, 10, 11, 12])
close = 15
assert([hours.length, hours.sum()], [6, 69])
hours
# return: [9,10,11,12,13,14]
- NUC 148 adds two range operators:
START..<ENDlists the integers fromSTARTup to, but not including,END, andSTART..=ENDlists them throughEND. A range is an ordinary list, sohours.lengthandhours.sum()read it as they read a list literal. hours = open..<closeis a standing declaration, so the hours follow the shift's bounds when it is extended. Both bounds must be integers, a range holds at most 100,000 items, andclose..<openis empty. See the root contract.
Population instance removal
Removing a car keeps a parking lot's free spaces live
class Car(plate, level):
this.plate = plate
this.level = level
capacity = 3
free = capacity - Car.length
upstairs = Car.filter(car -> car.level == 2).map(car -> car.plate)
van = Car("AB-12", 1)
cab = Car("CD-34", 2)
bus = Car("EF-56", 2)
assert([free, upstairs], [0, ["CD-34", "EF-56"]])
Car.remove(cab)
assert([free, upstairs], [1, ["EF-56"]])
Car.map(car -> car.plate)
# return: ["AB-12","EF-56"]
- NUC 162 adds
Name.remove(instance), which removes an instance from its class's population in one statement: it deletes every property the instance holds and then the instance, asdelete cab.level,delete cab.plateanddelete cabdo. - The free spaces and the cars upstairs are standing declarations over the
population, so they follow the departing car, while
delete cabalone would still raiseTypeError("Cannot delete object 'cab'")as long as the car holds its plate and level. See the root contract.
Distances of reasoning selections
Distances tell an alarm's direct causes from the readings behind them
temp = 31
humidity = 70
heat = temp > 30
damp = humidity > 60
alarm = heat && damp
layers = alarm |> why |> distances
assert(layers, [0, 1, 1, 2, 2])
wind = 4
alarm = heat && damp && wind < 10
layers
# return: [0,1,1,1,2,2]
- NUC 164 adds the final reasoning stage
|> distances, which gives each step of a selection its distance: the number of dependency edges between the step and where the walk that selected it began.alarm |> why |> distancesputs the alarm at 0, the heat and the damp it reads directly at 1, and the readings behind them at 2. - The distances stay live the way the explanation does: once the alarm also reads the wind, the wind joins the direct causes at 1, while the temperature and the humidity stay two steps away. See the root contract.
Population clearing
Clearing a closed day's orders keeps a till's takings live
class Order(item, price):
this.item = item
this.price = price
open = Order.length
takings = Order.map(order -> order.price).reduce((total, price) -> total + price, 0)
Order("tea", 4)
Order("jam", 6)
assert([open, takings], [2, 10])
Order.clear()
assert([open, takings], [0, 0])
Order("rye", 5)
[open, takings]
# return: [1,5]
- NUC 167 adds
Name.clear(), which removes every instance in a class's population in one statement, each with every property it holds, asName.remove(instance)removes one. - The open orders and the takings are standing declarations over the
population, so they follow the closed day down to zero and the first order
of the next day. Without
clear, the day closes with a loop,for order in Order: Order.remove(order). See the root contract.
Entries of reasoning selections
Entries explain a delivery fee with the value of each part
base = 5
distance = 12
weight = 3
fee = base + distance * 2 + weight
parts = why fee |> stated |> entries
assert(parts, [["base", 5], ["distance", 12], ["weight", 3]])
weight = 8
assert(parts, [["base", 5], ["distance", 12], ["weight", 8]])
fee = base + distance * 2
parts
# return: [["base",5],["distance",12]]
- NUC 169 adds the final reasoning stage
|> entries, which gives each step of a selection as a[node, holds]pair: the step's name and the value it holds.why fee |> stated |> entrieslists the facts the fee rests on, each with its value, which|> nodesand|> holdsgive only as two separate lists. - The pairs stay live the way the explanation does: a heavier parcel changes the weight's value, and once the fee no longer reads the weight, its pair leaves the list. See the root contract.
Predicate population removal
Removing cancelled bookings keeps a hotel's free rooms live
class Booking(guest, nights, cancelled):
this.guest = guest
this.nights = nights
this.cancelled = cancelled
rooms = 3
free = rooms - Booking.length
stays = Booking.map(booking -> booking.nights).reduce((total, count) -> total + count, 0)
Booking("ana", 2, false)
Booking("bo", 3, true)
Booking("cy", 1, true)
assert([free, stays], [0, 6])
Booking.removeWhere(booking -> booking.cancelled)
assert([free, stays], [2, 2])
Booking("di", 4, false)
[free, stays]
# return: [1,6]
- NUC 172 adds
Name.removeWhere(predicate), which removes every instance of a class's population that a predicate holds for, in one statement, each with every property it holds, asName.remove(instance)removes one. - The free rooms and the nights booked are standing declarations over the
population, so they follow the cancelled bookings out and the next
booking in. Without
removeWhere, the cancellations leave in a loop,for booking in Booking.filter(booking -> booking.cancelled): Booking.remove(booking). See the root contract.
Guarded for loops
Guarded loops cool only the rooms above a limit
class Room
Room(temp=29)
Room(temp=21)
hot = Room.count(room -> room.temp > 25)
cooled = 0
def cool(limit): for room in Room if room.temp > limit: room.temp -= 2; cooled += 1
cool(25)
assert: [hot, cooled], [1, 1]
cool(20)
[hot, cooled]
# return: [0,3]
- NUC 174 lets an explicit
forheader take a guard, as a comprehension'sforclause does: the body runs only for the items for which the condition afterifholds. The loop means exactlyfor room in Room: if room.temp > limit: .... - The guard is tested once for each room each time
coolruns:cool(25)cools only the room at 29 degrees, which stays above 25 at 27, andcool(20)cools both rooms, socooledcounts three coolings andhotfollows every change. See the root contract.
Comma-free named arguments
Named arguments describe each room without commas
class Room
den = Room(temp=18 target=20)
cold = Room.count(room -> room.temp < room.target)
assert: cold, 1
den.temp = 22
assert: cold, 0
Room(temp=15 target=19)
cold
# return: 1
- NUC 175 lets a named argument follow another without
a comma, as an explicit object property follows another:
Room(temp=18 target=20)means exactlyRoom(temp=18, target=20). Each name and its=already mark where the next argument begins. coldcounts the rooms below their target and follows every change: warming the den to 22 degrees leaves no room cold, and the room that arrives at 15 degrees for a target of 19 makes one cold again. Positional arguments and method calls keep their commas. See the root contract.
Transitive property paths
Transitive paths keep a site ready as its links change
class Page
about = Page(live=true)
home = Page(links=[about])
ready = all p in home.links+: p.live
assert: ready, true
about.links = [home]
assert: ready, false
home.live = true
ready
# return: true
- NUC 179 adds the transitive property paths
OBJECT.NAME+andOBJECT.NAME*.home.links+lists every page that followinglinksone or more times fromhomereaches, nearest first and each page once, andhome.links*listshomeitself first. A list of links fans out to its pages, and a page already reached is not followed again, so the walk ends even where the links go round in a circle. readyholds when every page that the home page leads to is live, and it follows every link it read. The about page is live, so the site starts ready. Once the about page links back to the home page, the home page is reached as well, and the site waits until it goes live too. See the root contract.
Multi-axis subscripts
Multi-axis subscripts read the down words of a crossword
rows = ["bats", "aloe", "dent"]
down = [0, 1, 2, 3].map(c -> rows[:, c].join(""))
assert: down, ["bad", "ale", "ton", "set"]
rows = ["hats", "aloe", "dent"]
down
# return: ["had","ale","ton","set"]
- NUC 180 adds multi-axis subscripts
VALUE[AXIS, AXIS, ...], the axis-per-comma subscripts of NumPy, Julia and MATLAB. Each axis is an index or a slice, applied from the outside in:rows[1, 2]readsrows[1][2], and a slice axis keeps the items it takes and applies the remaining axes to each of them, sorows[:, c]reads columnc, one letter from every row. downspells the crossword's down words, one for each column, and follows every change: once the first across word is "hats", the first down word is "had". Each column is chosen by the callback's own parameterc, which a nested callback such asrows.map(r -> r[c])cannot read. See the root contract.
Destructured list parameters
Destructured list parameters score a league table
scores = [[2, 1], [0, 0], [3, 1]]
points = scores.sum([home, away] -> home > away ? 3 : home == away)
assert: points, 7
scores.push([1, 1])
points
# return: 8
- NUC 182 adds list patterns as parameters. A
parameter written
[home, away]takes one argument and names its items by position:homereads the item at position 0 andawaythe item at position 1, asscore[0]andscore[1]would. A pattern stands alone before an arrow, as here, or among the other parameters of a lambda, a function or a method. pointsgives three points for each home win and one for each draw, assumcountshome == awayas1or0, and follows every change: the draw thatpushadds raises it from 7 to 8. The names are locals of each call, as parameters are. See the root contract.
Kotlin aggregate method aliases
Kotlin aggregate names keep the revenue and the largest and smallest orders live
class Order(total): this.total = total
Order(30)
Order(45)
revenue = Order.sumOf(o -> o.total)
largest = Order.maxOf(o -> o.total)
smallest = Order.minOf(o -> o.total)
assert: [revenue, largest, smallest], [75, 45, 30]
Order(20)
[revenue, largest, smallest]
# return: [95,45,20]
- NUC 183 adds Kotlin's
sumOf,maxOfandminOfas method aliases ofsum,maxandminon lists and class populations:Order.sumOf(o -> o.total)is exactlyOrder.sum(o -> o.total), with the same arguments, result, liveness and errors. revenue,largestandsmallestfollow every order: the order of 20 raises the revenue to 95 and becomes the smallest. An empty list or class gives0,-InfinityandInfinity, assum,maxandmindo. See the root contract.
List and population chunks
Chunks keep a cinema's seats in rows of three
seats = ["A1", "A2", "A3", "B1", "B2"]
rows = seats.chunk(3)
assert: rows, [["A1", "A2", "A3"], ["B1", "B2"]]
seats.push("B3", "C1")
rows
# return: [["A1","A2","A3"],["B1","B2","B3"],["C1"]]
- NUC 184 adds
chunk(size)to lists and class instance lists.seats.chunk(3)splits the seats, in order, into consecutive rows of three, as lodash'schunk, Kotlin'schunkedand Python'sitertools.batchedsplit a sequence; the last row holds the seats that remain and may be shorter. rowsis live: B3 completes the second row and C1 starts a third. On a class,Seat.chunk(3)splits its instances in the order they were created, and each row holds the instances themselves. A size that is not a positive whole number raisesTypeError("chunk expects a positive whole number"). See the root contract.
Swift boundary and predicate method aliases
Swift method names keep a release gate live
branch = "release/2.4"
build = "app-2.4.zip"
checks = [{ok: true}, {ok: false}]
gate = [branch.hasPrefix("release/"), build.hasSuffix(".zip"), checks.allSatisfy(c -> c.ok)]
assert: gate, [true, true, false]
checks.pop()
gate
# return: [true,true,true]
- NUC 186 adds Swift's
hasPrefixandhasSuffixto strings, as names ofstartsWithandendsWith, andallSatisfyto lists and class populations, as a name ofevery:checks.allSatisfy(c -> c.ok)is exactlychecks.every(c -> c.ok), with the same arguments, result, liveness and errors. gatefollows every change: once the failing check is popped, every check passes. An empty list or class satisfiesallSatisfy, as it satisfiesevery. See the root contract.
Implicit targets in class-level conditionals
Implicit targets state an order's perks once
class Order
if $Order.vip:
.tier is gold
.shipping is 0
.gift = "mug"
.points is 2
.support = "phone"
o = Order()
assert: [o.tier, o.shipping], [undefined, undefined]
o.vip = true
[o.tier, o.shipping, o.gift, o.points, o.support]
# return: ["gold",0,"mug",2,"phone"]
- NUC 188 lets a class-level conditional name its class
once. In the suite of
if $Order.vip:, an assignment that begins with a dot states a property of that class:.tier is goldis$Order.tier is goldand.gift = "mug"is$Order.gift = "mug". - The suite is the same live rule as its written-out spelling:
ohas no perks until it turns VIP, and then every line applies to it.elseand nested suites keep the class; function and class bodies do not. See the root contract.
None quantifiers
None quantifiers keep recalled products off the shelf
class Product
eggs = Product(recalled=true, listed=true)
safe = none p in Product: p.recalled && p.listed
stocked = none p in Product: p.listed && p.empty
assert: [safe, stocked], [false, true]
milk = Product(listed=true, empty=true)
assert: stocked, false
eggs.listed = false
assert: safe, true
milk.listed = false
stocked
# return: true
- NUC 189 adds the quantifier
none NAME in COLLECTION: CONDITIONbesideall,anyand the counts. It holds when the condition holds for no member:safewhile no recalled product is listed, andstockedwhile no listed product is empty. - Both claims stay live. The listed recalled eggs break
safeand the empty milk breaksstocked; taking each off the shelf mends its claim. See the root contract.
List transposition
Transposition keeps the months of a sales table live
sales = [[3, 5, 2], [4, 1, 6], [2, 2, 2]]
months = sales.transpose()
assert: months, [[3, 4, 2], [5, 1, 2], [2, 6, 2]]
sales.push([1, 0, 4])
months.map(m -> m.sum())
# return: [10,8,14]
- NUC 190 adds
transpose()to lists of rows. Each row ofsalesis a product and each column a month, sosales.transpose()lists the months, each with every product's sales. monthsis live: a new product's row adds its sales to every month, andm.sum()then totals each month. The rows must be lists of one length, ortransposeraises aTypeError. See the root contract.
Counting quantifiers
Counting quantifiers keep every match to two players
class Match
class Player
final = Match()
semi = Match()
Player(match=final)
Player(match=final)
Player(match=semi)
fair = all m in Match: exactly 2 p in Player: p.match == m
assert: fair, false
Player(match=semi)
assert: fair, true
Player(match=final)
fair
# return: false
- NUC 176 adds the counting quantifiers
exactly COUNT NAME in COLLECTION: CONDITION,at least COUNT NAME in COLLECTION: CONDITIONandat most COUNT NAME in COLLECTION: CONDITIONbesideallandany. Each counts the members for which its condition holds and compares that number with the count. fairholds when every match has exactly two players. Its condition reads the bindermof the enclosingall, which a callback cannot read, so the nested count needs no helper rule onMatch. The semifinal waits for its second player, and a third player in the final breaks the rule again. See the root contract.
F-strings and string templates
F-strings and string templates keep a shop's price tags live
class Item(name, price):
this.name = name
this.price = price
currency = "EUR"
$Item.tag = f"{$Item.name}: {$Item.price} {currency}"
$Item.label = "${$Item.name} costs $currency ${$Item.price}"
mug = Item("Mug", 8)
assert: mug.tag, "Mug: 8 EUR"
mug.price = 9
currency = "USD"
assert: mug.label, "Mug costs USD 9"
mug.tag
# return: "Mug: 9 USD"
- NUC 177 adds Python's f-strings, where
fbefore a quote interpolates each{expression}, and Kotlin's string templates, where a quoted string interpolates${expression}and$name. Template literals keep their behavior. - Both class-level rules follow every change: a new price and a new
currency reach the tag and the label of every item. A list or an object
interpolated in the new forms renders as JSON, as the next section shows,
and
\$writes a dollar sign. See the root contract.
Interpolated lists and objects as JSON
JSON interpolations show a board's grid in its summary
class Board(grid):
this.grid = grid
$Board.summary = f"Board {$Board.grid} has {$Board.grid.length} rows"
board = Board([[0, 1], [1, 0]])
assert: board.summary, "Board [[0,1],[1,0]] has 2 rows"
board.grid.push([1, 1])
board.summary
# return: "Board [[0,1],[1,0],[1,1]] has 3 rows"
- NUC 178 renders a list, an object or an instance
interpolated in an f-string or a string template as compact JSON, as
JavaScript's
JSON.stringifywrites it, so the rows of a grid keep their brackets. Template literals keep rendering a list as0,1,1,0. - The summary follows the grid in place: pushing a row reaches it at once, as any read of the grid would. See the root contract.
Mustache string interpolation
Quoted strings interpolate mustache braces
class Sheet(cells):
this.cells = cells
$Sheet.message = 'Sheet {{$Sheet.cells}} has {{$Sheet.cells.length}} rows'
sheet = Sheet([[1, 2], [3, 4]])
assert: sheet.message, "Sheet [[1,2],[3,4]] has 2 rows"
sheet.cells.push([5, 6])
sheet.message
# return: "Sheet [[1,2],[3,4],[5,6]] has 3 rows"
- NUC 187 reads
{{expression}}in a quoted string as an f-string reads{expression}, the double braces of Mustache, Handlebars and Jinja, so the message needs no prefix and the cells render as JSON. - Single braces and double braces that hold no single expression stay
text, as in
'{"rows":2}'and'{{a b}}', and a quoted string without a mustache interpolation reads as it did, a${...}template included. See the root contract.
Padding method aliases
Padding aliases keep a help desk's ticket board aligned
ticket = "7"
title = "Printer"
row = ticket.rjust(4, "0") + " " + title.ljust(10, ".") + "|"
assert(row, "0007 Printer...|")
ticket = "128"
title = "Badge reader"
assert(row, "0128 Badge reader|")
row
# return: "0128 Badge reader|"
- NUC 157 adds the padding names of Python and Ruby,
rjustandljust, and of C#,PadLeftandPadRight, as aliases ofpadStartandpadEnd:ticket.rjust(4, "0")isticket.padStart(4, "0")andtitle.ljust(10, ".")istitle.padEnd(10, "."), so the row gives exactly what its accepted spelling gives. rowstays live, so a new ticket and title realign it, and a title that already holds ten characters, such as"Badge reader", is not padded. See the root contract.
Reactive hypotenuse
Math.hypot keeps a drone's distance to its landing pad live
drone = {x: 7, y: 10}
pad = {x: 1, y: 2}
distance = Math.hypot(drone.x - pad.x, drone.y - pad.y)
assert(distance, 10)
drone.x = 16
assert(distance, 17)
drone.y = 22
assert(distance, 25)
distance
# return: 25
- NUC 159 adds
Math.hypot(value, ...), the square root of the sum of the squares of its arguments: the straight-line distance between two points from the differences of their coordinates, or the length of a vector from its components, as JavaScript'sMath.hypotand Python'smath.hypotcompute it. distanceis a standing declaration, so it follows every move of the drone. Each distance here is whole, asMath.hypotgives it exactly for every integer Pythagorean triple, and it is what((drone.x - pad.x) ** 2 + (drone.y - pad.y) ** 2) ** 0.5gives, without squaring each difference by hand or overflowing for large coordinates. See the root contract.
Symmetric difference reasoning selections
Xor tells two alarms apart
smoke = 4
heat = 60
humidity = 70
haze = smoke * 2
fire = haze > 5 && heat > 50
fog = haze > 5 && humidity > 60
apart = why fire |> xor(why fog) |> stated
assert(apart.map(step -> step.node), ["heat", "humidity"])
fire = haze > 5 && heat > 50 && humidity < 90
assert(apart.map(step -> step.node), ["heat"])
- NUC 139 adds the reasoning stage
|> xor(OTHER), the symmetric difference of two selections.why fire |> xor(why fog)keeps the steps of the fire alarm's explanation whose node the fog alarm's does not hold, then the steps of the fog alarm's explanation whose node the fire alarm's does not hold. The haze and the smoke behind both alarms are left out, so what remains tells the two alarms apart. - The result is still a selection, so
|> statednarrows it to the facts, the heat and the humidity, and it stays live: once the fire rule also checks the humidity, the humidity stands behind both alarms and only the heat sets the fire alarm apart. See the root contract.
Negated membership with !in
Kotlin's !in keeps an access rule live
blocked = ["mallory"]
class User(name):
this.name = name
$User.allowed = $User.name !in blocked
alice = User("alice")
mallory = User("mallory")
assert([alice.allowed, mallory.allowed], [true, false])
blocked.push("alice")
assert(alice.allowed, false)
alice.allowed
# return: false
- NUC 135 adds Kotlin's
item !in collection, the same test asitem not in collection: each user'sallowedfollows theblockedlist, as it does withnot in. !andinare written together, as Kotlin writes them;! inkeeps its syntax error. Rules render the test asnot in. See the root contract.
Rust library embedding
- A library caller can copy a populated
nucleoid::Runtimewithlet mut branch = runtime.clone();and continue either runtime withrun. Rust's standardclone_fromalso supports replacing an existing destination. - Each copy retains the model, live dependencies, histories, functions, class rules, objects and private execution bookkeeping. Cloning runs no program or rule and preserves assertion failures and their executed count.
- Mutable state is independent: changing, deleting, clearing or draining diagnostics in one runtime does not change the other. Immutable function syntax may be shared, and existing object IDs remain local to each copy.
- This is a Rust library API, not new Nucleoid syntax. See NUC 166 and the normative contract for the complete copy semantics and unchanged runtime limits, including run-time value nesting.
Colon-free number-led object values
Number led object values omit redundant colons
record = {width 3 height 4 scale 2}
assert(record.width, 3)
assert(record.height, 4)
assert(record.width * record.height * record.scale, 24)
1
# return: 1
- NUC 168 permits a colon omission only when an existing key is immediately followed by a number token. The entire ordinary value expression still parses first; explicit colons and commas remain valid, and canonical output still contains colons.
- Every original whole-input retry wins before the new fallback, including accepted parses that fail at runtime. Names, booleans, strings, unary signs and separators after a key do not qualify. Shorthand, block syntax, dependencies and object behavior are unchanged.
- See the root contract and reference.
Isolated reasoning selections
Isolated selections find independent facts.
base = 2
result = base + 1
free = 5
lonely = model |> isolated
assert(lonely.map(s -> s.node), ["free"])
one = base |> isolated
assert(one.map(s -> s.node), ["base"])
empty = model |> except(model) |> isolated
assert(empty, [])
1
# return: 1
- NUC 170 filters a selection to the intersection of its original origins and outcomes. A one-step selection can keep a node whose dependents are outside that selection; the empty selection stays empty.
- Paths through omitted nodes count, cycles exclude their own steps, and reasoning observers cut paths off. Records, distances, walk direction and live observations are retained. The word stays an ordinary identifier outside the contextual stage; every accepted whole-input parse wins first.
- See the root contract and reference.
Benchmark
This is the comparation our sample order app in Nucleoid IDE against MySQL and Postgres with using Express.js and Sequelize libraries.

Performance benchmark happened in t2.micro of AWS EC2 instance and both databases had dedicated servers with no indexes and default configurations.
https://github.com/NucleoidAI/benchmark
As seen in the chart, for applications with average complexity, Nucleoid's performance is close to linear because of on-chain data store, in-memory computing model as well as limiting the IO process.
โญ๏ธ Star us on GitHub for the support
World Models are an emerging field and thanks to declarative logic programming, we have a brand-new approach to building World Models. Join us in shaping the future of AI!
Contributors
NucBot | canmingir | 322332 | dependabot[bot] | francisco-giancarelli-crombie | Gulshanaggarwal | CanPacis |
durulkoca | halilcengel | EnesKeremAYDIN | russle-smith | russellgray |
Generated by NucBot
Reusing compiled programs from Rust
nucleoid::CompiledProgram::new(source: &str)validates and owns a program once. The original source string can then be changed or dropped.runtime.run_compiled(&program)executes it without reparsing, returning the sameResult<Value>asruntime.run(original_source). Reuse one immutable program with current state in the same runtime or across independent runtimes.- Every invocation keeps
run's fresh scope, atomic transaction, dependency propagation, histories, exact diagnostics and assertion accounting. There is no new Nucleoid spelling, built-in, flag or mutable AST API. - See NUC 171, the library reference and the normative contract.
Atomic compiled batches from Rust
runtime.run_compiled_batch(&programs)borrows a slice of immutableCompiledPrograms and returnsResult<Vec<Value>>in input order without reparsing. Each program keeps its fresh scope, original source positions, propagation and deferred suites; a return ends that program only.- One transaction commits only when every program succeeds. An execution error stops before later programs and rolls back all batch state and graph writes. Reached assertion counts and diagnostics remain; failed assertions are not execution errors.
- Empty input is a no-op returning an empty vector. Checked result allocation
happens before runtime mutation and reports
TypeError("Cannot allocate compiled batch results")without a source position. - Existing APIs, syntax and ordinary result-value ownership remain unchanged.
See NUC 173 in
docs\nuc-0173.md, the Rust-library batch reference indocs\README.md, and the normative "Atomic compiled program batches" section innucleoid.spec.md.
Jelajahi proyek terkait
Memuatโฆ