This document is the normative specification of Essential Arra: the smallest character-complete form of the language and the semantic kernel around which future extensions may grow.
The earlier, broader design is preserved in Git history but is not this specification. Features listed as deferred here are outside the language until they are reconsidered against the Essential kernel.
Arra is a left-to-right, valence-aware array-functional language where subject-first mapping, coherent hooks, shapes, layouts, and effects remain visible in the source model.
Essential Arra preserves eight commitments:
app/pat, project/assign, and iter/gen remain
visible in the language.The reduction removes breadth, not weirdness.
Evaluation is left-to-right. An expression is a leading value followed by a sequence of projections. Every projection consumes the result to its left.
value transform consume
array 'map f 'filter p 'fold (⟦_; _⟧ +) 0
Projection chains associate strictly to the left:
x f g
means:
app(app(x, f), g)
All symbolic operators have equal precedence and associate left-to-right:
a + b * c
means:
(a + b) * c
Custom precedence and associativity declarations are not supported.
Everything that transforms a subject is written after that subject. The same order applies at the value, type, and pattern levels:
x Some // construct
a Option // form a type
x Some // deconstruct in pattern position
Expression context resolves the first form through app; pattern context
resolves the third through pat. Nullary constructors such as None are
unchanged. Nested construction and deconstruction associate left-to-right:
x Ok Some
Multi-parameter type constructors consume a tuple, following the readable postfix convention established by OCaml:
a Option
(e, a) Result
(k, v) Map
Shapes are postfix transformations in the same chain:
a Option[n] // array of optional a
a[n] Option // optional array
Type parameters precede the type constructor in declarations, and constructor payloads precede their constructor:
type a Option ← None | a Some
type (e, a) Result ← e Err | a Ok
Hook declarations give the static selector or dynamic formation operand before
:, then declare the complete mapping type:
op + : ⟦I64; I64⟧ → I64
op - : I64 → I64
fun ∀ (n : Nat) ⇒ sum : I64[n] → I64
pat Positive : I64 → I64 Option
iter ∀ (n : Nat) a b ⇒ 'map (a → b) : a[n] → b[n]
project .field : Record → Value
assign .field : ⟦Record; Value⟧ → Record
app (a → b) : a → b
An implementation names dynamic app, iter, or gen formation operands in
the head. Its body receives only the declared invocation domain.
A checked value definition may likewise fuse its type and body:
distance : ⟦Point; Point⟧ → F64 ←
⟦left; right⟧ → ...
Bodyless signatures remain the interface form. An implementation may supply an
inferred name ← expression without repeating its interface signature; the
expression is checked against that authoritative interface type. An optional
implementation annotation must agree exactly. A local implementation cannot
combine a separate signature with a fused annotation.
Every function literal is a conditional function. An ordinary lambda is the degenerate case with one irrefutable path:
square ← x → x * x
A parameter vector declares a multivalent function directly:
add ← ⟦left; right⟧ → left + right
Its patterns bind the structural domain positions; it is not a tuple pattern.
Conditional functions may use the same structural domain across clauses:
compare ←
⟦left; right⟧ ∧ left < right → Less
⟦left; right⟧ ∧ left > right → Greater
_ → Equal
All explicit vectors in one clause list have equal valence. Bare _ → body
discards a domain already fixed by a signature, ascription, hook contract,
higher-order parameter, or vector-headed sibling clause. Without such a demand
it remains unary. This elision is applied only after a function domain is known;
it never determines ambiguous hook selection.
Several clauses form one ordered conditional function. Layout separates
clauses; ; is the explicit inline separator:
unwrap ←
x Some → x
None → default
unwrapInline ← (x Some → x; None → default)
This is Arra’s adaptation of Cheng and Parreaux’s Ultimate Conditional Syntax. It replaces separate block-lambda, guard, match, and view-pattern systems with paths built from four structural forms:
| Form | Meaning |
|---|---|
p ← e |
define or unconditionally bind p to e |
e ⇒ p |
conditionally match e against p and introduce its evidence |
a ∧ b |
continue a successful path, with earlier bindings in scope |
path → result |
map a successful path to its result |
⇒ and ∧ are structural only when they occur unparenthesized at the top
level of a conditional path. Elsewhere they remain ordinary hookable symbolic
operators. Parentheses therefore escape from path grammar into expression
grammar: (a ∧ b) ⇒ True → result calls op ∧, then tests its result.
Likewise, (a ⇒ b) ⇒ True → result calls op ⇒. Their ASCII spellings are
=> and &&; the ordinary -> spelling of → remains valid. A watcher may
render the Unicode forms. No branch-leading marker or else keyword exists:
layout or ; separates alternatives, and _ is the residual path.
The arrows are related rather than interchangeable. ← keeps definitions
name-first. ⇒ introduces conditional evidence, at both the type level
(∀ a ⇒ ...) and the term level (e ⇒ p). → describes production, in both
function types and conditional clauses.
The first form in a clause is either a pattern on the clause-list subject or a projection suffix whose missing left operand is that subject:
classify ←
< 0 → Negative
= 0 → Zero
_ → Positive
consume ←
safeHead ⇒ x Some ∧ x valid → x process
_ → fallback
Given subject s, the first function expands as if it contained s < 0 and
s = 0. In the second, safeHead ⇒ x Some means
s safeHead ⇒ x Some. Projection elision applies uniformly to recognizable
symbolic, whitespace, traversal-name, and field suffixes:
< 0
parse validate ⇒ ast Ok
'first valid ⇒ x Some
.price ⇒ price Some
An initial pattern may name the subject while later suffixes still elide it:
consumeWithSource ←
xs ∧ safeHead ⇒ x Some ∧ x valid → ⟦xs; x⟧ process
_ → fallback
The implicit subject is fixed for one clause-list level. A successful pattern
introduces names but never silently changes that subject. In
safeHead ⇒ x Some ∧ x valid, the final condition must name x; writing only
valid would apply valid to the original clause-list subject.
A computed result can instead establish a nested clause-list subject:
handleRequest ←
decode ⇒
message Ok
∧ message authenticate ⇒
user Some → ⟦user; message⟧ process
None → Unauthorized
error Err → error BadRequest
After decode ⇒, the decoded result is the subject of the nested message Ok
and error Err clauses. After authenticate ⇒, the authentication result is
the subject of user Some and None. Every name is introduced by an incoming
pattern, a successful ⇒ match, or an enclosing lexical scope.
The explicit nested form is equivalent:
handleRequest ← (
decode ⇒ (
message Ok
∧ message authenticate ⇒ (
user Some → ⟦user; message⟧ process;
None → Unauthorized
);
error Err → error BadRequest
)
)
Failure of a path resumes at the next clause in the nearest enclosing clause
list. Failure may not escape the complete conditional function: every clause
list must be proved exhaustive. Code that wants source-level failure writes an
explicit fallback such as _ → () raise. Clauses and path components execute
once, strictly left-to-right; later components are not evaluated after failure
and later clauses are not evaluated after success. pat hooks themselves
remain pure, while ordinary expressions producing computed scrutinees may carry
effects.
Totality uses a conventional structural pattern matrix. Complete finite algebraic-constructor and Boolean cases are proved, recursively through tuples and records. An exact static-length array pattern participates only when each element pattern is exhaustive. A structural subject pattern may be followed by irrefutable matching or binding components without losing its coverage contribution. Nested clause lists are checked recursively; a total nested list cannot fall through to the outer alternative, although effects from computing its subject remain.
Dynamic arrays, scalar literals over infinite domains, pat extractors,
computed evidence, and guarded path components remain conservative and
therefore require an explicit residual clause. Once a reachable clause prefix
covers the subject domain, later clauses are unreachable and do not contribute
effects. Coverage changes static upper bounds only—never clause order or runtime
behavior. A clause proved unreachable produces a warning with a stable
diagnostic code; conservative domains produce no warning before their required
fallback.
A lone lowercase name followed by → is always an irrefutable binder:
valid → body // bind the subject as valid
It is never parsed as an implicit call to a predicate named valid. The
unambiguous predicate form is:
valid ⇒ True → body // apply the subject to valid, require True
If a function-typed name in the binder form strongly suggests this missing
⇒ True, the compiler reports a targeted diagnostic. The same applies when a
top-level ⇒ or ∧ was plausibly intended as a hooked expression: the
diagnostic explains that the token is structural in this position and suggests
parenthesizing the expression, followed by ⇒ True when its result is the
condition. Parsing itself never uses type information or backtracking.
Parentheses remain unambiguous by their top-level structural tokens: →
identifies a conditional function, , without → identifies a tuple, and
neither identifies grouping or a sequential block. Within a conditional
function, layout or explicit ; fixes clause boundaries. A same-line ∧ or an
indented line beginning with ∧ extends the current path.
Recursion is explicit. rec name ← expression creates a singleton recursive
group; rec followed by a declaration block creates a mutually recursive
group. The two forms have one semantics: all names in the group are introduced
simultaneously and are in scope throughout every member’s right-hand side.
Source order does not restrict references within the group.
Within the block, value bindings are the recursive group members. Signatures and other declarations retain their ordinary roles and do not become recursive term bindings. Evaluation does not execute the group eagerly as a sequence of independent bindings; it creates the recursive environment used by its members. A non-recursive value binding cannot refer to itself or to later bindings merely because they are textually nearby.
The singleton syntax is not a weaker recursion mechanism or implicit inference rule. It is the concise spelling of a one-member group.
A nonrecursive value binding may bind a name, discard with _, or destructure
nested tuples and structural records. Record fields may use puns. An annotation
may wrap the complete pattern or any nested binding pattern:
(left, right) ← pair
{x, y: (top, _)} ← record
((row, column) : (Nat, Nat)) ← coordinate
The initializer evaluates exactly once before any introduced name enters scope. All names in one pattern become visible simultaneously after that evaluation; none is visible in the initializer. Lowering binds one hidden value and derives ordinary tuple/record projections from it. Duplicate names are rejected across the complete nested pattern.
Binding destructuring is structural and never crosses a nominal boundary.
Literal, constructor, array, extractor, guarded, and other refutable patterns
remain conditional-function forms. Destructuring never silently introduces
Fail, and recursive declarations admit name binders only.
Essential Arra exposes nine statically resolved hook heads:
| Head | Trigger | Request direction |
|---|---|---|
app |
subject-first adjacency | input |
op |
postfix unary or infix binary symbol | input |
fun |
lower-case function family | input and demand |
pat |
named postfix deconstruction | input |
project |
field read | input |
assign |
field replacement | input |
iter |
named structure-consuming traversal | input |
gen |
named structure-producing traversal | output |
to |
demanded conversion | output |
Hooks are compile-time syntax and type mappings. Lowering retains only direct implementation references; there is no runtime dispatch table.
Unary adjacency is subject-first:
x f = app(x, f)
Prelude supplies ordinary function application:
app ∀ (e : Effects) a b ⇒
(a →⟪e⟫ b) : a →⟪e⟫ b
There is no conventional function-first adjacency. Given f : A → B, f a
does not reverse the operands.
Function domains preserve valence:
nullary : ⟦⟧ → R
unary : A → R
tupled : (A, B) → R
dyadic : ⟦A; B⟧ → R
curried : A → (B → R)
These are distinct types. Centered whitespace supplies the complete domain:
x f y // equivalent to ⟦x; y⟧ f
x f y g z // equivalent to (x f y) g z
The mapping at a centered site must be pure. Arguments evaluate exactly once in written order. An incomplete centered domain rejects rather than partially applying.
An invocation vector explicitly supplies a complete hook domain. _ is its
only residual hole:
f : ⟦A; B; C⟧ → D
⟦a; b; c⟧ f // D
⟦a; _; c⟧ f // B → D
⟦_; b; _⟧ f // ⟦A; C⟧ → D
⟦⟧ thunk // nullary invocation
Supplied positions evaluate once from left to right, followed by a dynamic formation operand. A residual captures supplied values, formation operands, and the already selected hook. Its missing positions retain original order and its effects remain latent until complete.
Unary postfix and binary infix operations use one op head:
op - : I64 → I64
op + : ⟦I64; I64⟧ → I64
x-
x + y
Arity is part of the mapping type. All operators have equal precedence and associate left-to-right. Sections do not exist; residuals are explicit:
⟦_⟧ -
⟦_; _⟧ +
⟦_; 1⟧ +
fun marks a statically selected lower-case family while preserving ordinary
postfix use syntax:
fun ∀ (n : Nat) ⇒ sum : I64[n] → I64
values sum
A local, constrained, module, or effect-operation value with the same exposed
name shadows the static family. Otherwise the request is keyed by that exposed
name and selected as a hook; dependency aliases therefore rekey the family. A
selected fun mapping may be reified when an expected mapping type fixes its
overload, but the family name itself is not a runtime marker.
Every app or op request first attempts direct resolution on the complete
operand and demanded result types. A unique direct hook is final. Only absence
of a direct match permits one compiler-owned structural schema:
app composes compatible functions;op maps over every position of a function’s complete domain;op aligns functions with equal complete domains;app and operators other than + recurse fieldwise over identical exact
closed records;app and op recurse cellwise over identical complete nonempty array frames;+ concatenates disjoint structural records.Function alignment preserves nullary, unary, and multivalent domains. Record fields use canonical order. Array frames use row-major order. Each step removes a function, exact record, or complete frame, so planning terminates at a smaller leaf request.
Structural resolution never backtracks, inserts conversion, crosses a nominal boundary, opens a record row, broadcasts, guesses rank, or consults effects. A leaf failure fails the selected plan.
For aligned functions:
f : ⟦a; b⟧ →⟪e₁⟫ c
g : ⟦a; b⟧ →⟪e₂⟫ d
op ⊕ : ⟦c; d⟧ →⟪e₃⟫ r
f ⊕ g : ⟦a; b⟧ →⟪e₁ | e₂ | e₃⟫ r
At invocation, f executes before g, then the leaf operation. Composition,
unary lifting, explicit invocation vectors, and longer left-associated trains
follow the same rule:
f g h
f + g + h
⟦_; _⟧ +
⟦_⟧ 'map parse
These elaborate to lambdas, direct applications, cases, and ordered lets. Core has no atop, fork, train, section, or invocation-vector node.
pat is the deconstruction dual of app:
pat Positive : I64 → I64 Option ←
n ∧ n > 0 → n Some
_ → None
For this Option extractor, u Some passes u to the subpattern and None
fails the current conditional path. The protocol is library-neutral: any
nominal two-alternative result with exactly one nullary alternative and one
unary alternative is valid, and the unary payload is the extracted value. The
same pure extractor is callable:
value (
n Positive → n use
_ → fallback
)
7 pat Positive
⟦_⟧ pat Positive
Constructors are built-in construction/deconstruction pairs:
x Some
x Some → x use
Named pattern hooks are pure and provide no solver refinements. Because extractor coverage is conservative, a conditional using one requires an explicit residual clause.
project handles reads and assign handles replacement:
project .field : Record → Value
assign .field : ⟦Record; Value⟧ → Record
record.field
record.(field ← value)
A project-only hook is a computed read-only property; no separate view
dispatch family exists.
Name quantification permits one implementation to abstract over a static
field identity:
fun ∀ (name : Name) a (rest : Fields)
| name ⟂ rest
⇒ get : {⟦name⟧: a | rest} → a ←
record → ⟦record⟧ project name
Literal selectors and canonical ordinal selectors such as .1 are Name
terms. Static names specialize before Core and never become runtime String or
Symbol values.
An iter head contains a traversal selector and one dynamic modifier formation
operand:
iter ∀ (e : Effects) (frame : Shape) (cell : Shape) (out : Shape) a b
⇒ 'map (a[cell] →⟪e⟫ b[out])
: a[frame; cell] →⟪e⟫ b[frame; out]
The mapper input shape chooses the unique suffix cell. The remaining prefix is the frame; the mapper output replaces the cell suffix. No rank search or broadcast occurs. A scalar mapper therefore consumes scalar cells at every frame position.
'fold makes its modifier boundary explicit:
xs 'fold reducer initial
reducer is the formation operand; xs and initial form the derived
invocation domain.
Rank-two selection uses ordinary hooks. Indices are zero-based. Spans are
half-open and require start ≤ stop ≤ extent; equal bounds select an empty
axis. Matrix, row span, and column span evaluate in that order. Rows validate
before columns. A 'slice result carries both selected extents existentially.
gen is selected using the demanded result container:
gen ∀ (e : Effects) a state
⇒ 'generate (state →⟪e⟫ (a, state) Option)
: state →⟪e⟫ a[_]
For the Option protocol shown, a finite generator stops at None. Generation
is library-neutral: the step may return any nominal two-alternative result with
one nullary stop alternative and one unary alternative carrying (element,
nextState). Different demanded targets may provide different implementations.
If no unique target is known, selection is ambiguous rather than defaulting a
container.
An exact regular-array generator instead takes its cardinality from the demanded frame:
gen ∀ (e : Effects) (frame : Shape) (cell : Shape) a state
⇒ 'generate (state →⟪e⟫ (a[cell], state))
: state →⟪e⟫ a[frame; cell]
The nonempty runtime-reifiable frame fixes the exact row-major step count. A zero extent invokes no step. The final state is discarded. Output cells match the demanded suffix exactly; generation does not pad, truncate, broadcast, or switch modes at runtime.
to is checked against a demanded target:
to : I64 → F64
x : F64 ← 3
value to F64
⟦_⟧ to F64
The target type is primary specificity and the source is secondary. At most one
implicit step is inserted. Conversions never chain, backtrack, or choose a
numeric default. Explicit to Target still selects one direct hook.
Each source request has a key: app; op plus glyph; fun plus exposed name;
pat plus selector; project/assign plus static field; iter/gen plus
traversal; or to.
Resolution is lexical:
app or op candidate matches, attempt the single
normalized structural plan from §2.3.Hook declarations are sequential, not block-wide. Dependency aliases rekey the selected declarations. Effects are accumulated only after selection and never rank candidates. A rejected trial cannot leak substitutions, evidence, or diagnostics into another candidate.
Ambiguity is a use-site error. The language deliberately permits declarations whose domains may intersect if no actual request sees an unresolved tie.
Specificity is structural over the whole request:
literal static identity
concrete nominal or structural type with literal dimensions
concrete type with shared dimension variables
concrete type with dynamic dimensions
structurally constrained variable
unconstrained variable
Shared variables impose equalities and therefore increase specificity. Array ranks are distinct rather than subtypes. A shape-polymorphic signature is less specific than one fixing the relevant shape. Operand specificity cannot ignore an expected result that distinguishes candidates.
A theory is a nominal compile-time relation over Type or Type → Type
parameters. It may declare:
theory a Equality
require equal
op = : ⟦a; a⟧ → Bool
law reflexive
⟦x : a⟧ ⇒ x equal x ≡ True
A model supplies evidence for one theory assignment. Its body repeats required prerequisite evidence, certifies each labelled hook with one ordinary value or primitive implementation, and explicitly assumes or discharges its laws:
model I64 Equality
certify Equality.equal with equalI64
assume reflexive
Models may be ground or quantified constructors:
model ∀ a | a Equality ⇒ (a Option) Equality
require a Equality
certify Equality.equal with equalOption
assume reflexive
Model-constructor premises must be strict structural subterms of the result head’s type arguments. Same-size or larger premises and bare-variable result heads reject, so recursive evidence construction terminates without search.
Generic value and hook schemes use the same flat constraint list. At a generic request, direct hooks still win. Only their absence allows a requirement selected from available constraint evidence. The chosen theory application and requirement are final; failed premise evidence does not reopen ordinary hook search. Determinations may infer dependent theory parameters only when the declared determinant side is fixed.
Model declarations participate in module views. model ... selects one exact
ground model or model constructor; models Theory selects the complete group.
Aliases and forwarding preserve exact declaration identity. Theories, model
constructors, evidence, certifications, and laws are fully erased before Core.
A hook is legal only in a module owning its operation family or a nominal type
in its signature. A distinct wrapper creates a new owned nominal type and is
the standard way to define a local operation over an external representation.
The corresponding ownership rule applies to models.
Selections are frozen at their lexical source positions. Importing or forwarding a module cannot change choices already resolved inside it. Whole-program specialization instantiates the selected declaration but may not select a replacement.
The kernel type system contains primitive scalars, nominal algebraic and record
types, structural products and extensible records, functions, regular shaped
arrays, existential dimensions, effect rows, and zero-cost distinct wrappers.
Its static kinds are:
| Kind | Meaning |
|---|---|
Type |
completed runtime value type |
Type → Type |
unary type constructor |
Nat |
one nonnegative array dimension |
Shape |
ordered dimension sequence |
Effects |
effect-row tail |
Name |
one static field identity |
Fields |
finite structural field map |
Effects variables form complete or trailing effect rows. Name and Fields
support computed field keys, open field maps, row sums, and disjointness
constraints. They are static and specialize before Core.
Representative forms:
a
(a, b)
{x: I64, y: F64}
{x: I64 | rest}
{⟦name⟧: a | rest}
{| left + right}
a[n]
a[n; m]
a[_]
a Option
(e, a) Result
(k, v) Map
a → b
a →⟪IO | E Fail⟫ b
∃(m : Nat) a[m]
Tuple and unit syntax elaborate to ordinal and empty structural records:
Unit, (), and {} denote the same empty product type. A quantified header
contains one flat list of theory and disjointness constraints. Expression
ascription (expression : Type) supplies local result demand for hook selection
and diagnostics.
Char is one Unicode scalar. A character literal defaults to Char, but a
demanded U8 context accepts the same literal through U+00FF. Character
patterns follow the same rule. String is immutable valid UTF-8 text and is not
a character array. Char[shape] uses dense fixed-width scalar lanes.
U8 contains values 0 through 255 and U8[shape] uses dense byte lanes.
Unconstrained integral literals default to I64; demanded U8 literals are
range-checked.
The source text boundary includes:
byteLength : String → Nat
characterCount : String → Nat
toCharacters : String → Char[_]
fromCharacters : ∀ (n : Nat) ⇒ Char[n] → String
codePoint : Char → Nat
charFromCodePoint : Nat →⟪UnicodeScalarError Fail⟫ Char
encodeUtf8 : String → U8[_]
decodeUtf8 : ∀ (n : Nat) ⇒ U8[n] →⟪Utf8Error Fail⟫ String
split : ⟦String; Char⟧ → String[_]
join : ⟦String[_]; String⟧ → String
parseI64 : String → I64 Option
showI64 : I64 → String
intern : String → Symbol
spelling : Symbol → String
Symbol is an atomic process-lifetime interned identity for one exact UTF-8
spelling. Construction performs no normalization. Symbol[shape] uses dense
identity lanes; entries live until process exit.
The binary/scalar conversion boundary includes:
u8ToI64 : U8 → I64
u8ToNat : U8 → Nat
i64ToU8 : I64 →⟪U8RangeError Fail⟫ U8
natToU8 : Nat →⟪U8RangeError Fail⟫ U8
u8ToChar : U8 → Char
charToU8 : Char →⟪U8RangeError Fail⟫ U8
type U8RangeError ←
I64 I64OutOfRange | Nat NatOutOfRange | Char CharOutOfRange
type Utf8Error ← {errorLength: Nat Option, validPrefix: Nat}
The same conversions have direct to hooks. UTF-8 decoding preserves the
longest valid prefix and an optional known rejected-subsequence length.
The IO boundary uses structured read and write failures:
type PlatformError ← {code: I64, domain: Symbol}
type IoError ← {
kind: Symbol,
operation: Symbol,
platform: PlatformError Option,
resource: Symbol Option
}
type TextIoError ← IoError Io | Utf8Error Decode
type WriteImpact ← DestinationUnchanged | DestinationMayBeModified
type WriteError ← {cause: IoError, impact: WriteImpact}
arguments : () →⟪IO | IoError Fail⟫ String[_]
readLine : () →⟪IO | IoError Fail⟫ String Option
readBytes : Symbol →⟪IO | IoError Fail⟫ U8[_]
readText : Symbol →⟪IO | TextIoError Fail⟫ String
writeBytes : ⟦Symbol; U8[_]⟧ →⟪IO | WriteError Fail⟫ ()
createBytes : ⟦Symbol; U8[_]⟧ →⟪IO | WriteError Fail⟫ ()
appendBytes : ⟦Symbol; U8[_]⟧ →⟪IO | WriteError Fail⟫ ()
writeBytesAtomically : ⟦Symbol; U8[_]⟧ →⟪IO | WriteError Fail⟫ ()
writeText : ⟦Symbol; String⟧ →⟪IO | WriteError Fail⟫ ()
createText : ⟦Symbol; String⟧ →⟪IO | WriteError Fail⟫ ()
appendText : ⟦Symbol; String⟧ →⟪IO | WriteError Fail⟫ ()
writeTextAtomically : ⟦Symbol; String⟧ →⟪IO | WriteError Fail⟫ ()
writeLine : String →⟪IO | IoError Fail⟫ ()
writeErrorLine : String →⟪IO | IoError Fail⟫ ()
write truncates or creates, create fails if the destination exists, and
append extends or creates. Atomic writes either report the destination
unchanged or conservatively report that it may have been modified. Expected
host failures remain source values, not runtime diagnostics.
arguments preserves host argument boundaries after --. readLine accepts
LF and CRLF input and returns the line without its terminator; a carriage return
not followed by LF remains content. None means EOF, while "" Some is an
actual empty line.
String concatenation uses +. Char, U8, Symbol, String, I64, and
Nat provide exact equality with Equality models. Raw F64 provides op =
but Prelude does not certify an Equality model for it. The current primitive
uses total runtime float equality, under which a NaN compares equal to itself.
I64, Nat, F64, Char, U8, and String provide < and >. Text
operations never normalize implicitly.
Records are permutation-insensitive finite maps from canonical Name identities
to types. Lower-case labels and ordinal selectors share this identity space;
.1, .01, and .0x1 are the same ordinal name. Duplicate canonical names
reject.
Open records retain genuine field-map expressions:
{x: T | rest}
{⟦name⟧: T | rest}
{| left + right}
Here rest, left, and right have kind Fields; name has kind Name.
left + right is permitted only under established disjointness. Generic
operations state support constraints explicitly:
fun ∀ (name : Name) a (rest : Fields)
| name ⟂ rest
⇒ get : {⟦name⟧: a | rest} → a
fun ∀ (left : Fields) (right : Fields)
| left ⟂ right
⇒ combine : ⟦{| left}; {| right}⟧ → {| left + right}
Value-level record + is disjoint concatenation after direct op + resolution.
record - name removes one statically selected field, where name may be a
literal selector such as .field or a quantified Name. Removal is a
compiler-owned form rather than a runtime op - request. project and assign
likewise accept literal or quantified static names. Row operations never
overwrite silently.
Record literals and irrefutable binding patterns support puns:
point ← {x, y, label: makeLabel x y}
{x, y} ← point
Tuple and unit values are records with ordinal and empty field maps. Their surface syntax does not create a separate product representation.
Transparent nominal record declarations, including parameterized declarations,
publish their exact fields and receive nominal field projection and assignment
hooks. They do not receive implicit structural to conversions. opaque
hides the representation from clients while retaining it internally for
checking and lowering. distinct preserves the wrapped runtime representation
but establishes a new nominal identity and hook ownership boundary.
Arrays of records use canonical struct-of-arrays storage. For a structural record:
{f₁: T₁, ..., fₖ: Tₖ}[n]
the stored layout is:
{f₁: T₁[n], ..., fₖ: Tₖ[n]}
Projection selects a column without traversing or copying. Indexing presents a logical scalar record assembled from the columns. Construction transposes fields into columns; traversals consume row views or equivalent temporary records and write produced fields into output columns. Nested records flatten recursively by field path.
This layout is observationally invisible because records have no identity, but the canonical columnar representation is a language invariant. Dense U8, Char, and Symbol columns retain their specialized lane storage.
A shape is an ordered sequence of Nat dimensions. The empty shape ε denotes
a scalar:
a[ε] = a
Shape terms are written in one semicolon-separated array suffix:
a[frame; cell]
For a mapper whose input has shape cell and an array whose shape is
a[frame; cell], the iterator applies the mapper to every cell in the frame. If
the mapper returns shape out, the result shape is b[frame; out].
a[frame; cell], (a[cell] → b[out])
→ b[frame; out]
Examples:
inc : I64 → I64
rowTotal : I64[m] → I64
transform : I64[p;q] → F64[q;p]
cube 'map inc
// input: I64[x;y;z]
// frame=[x;y;z], cell=ε, out=ε
// result: I64[x;y;z]
matrix 'map rowTotal
// input: I64[n;m]
// frame=[n], cell=[m], out=ε
// result: I64[n]
blocks 'map transform
// input: I64[r;p;q]
// frame=[r], cell=[p;q], out=[q;p]
// result: F64[r;q;p]
The mapper domain fixes the cell rank. Once cell is known, splitting the input
shape into a leading frame and trailing cell is unique. If the mapper remains
polymorphic over an unconstrained cell shape, inference does not try every
possible suffix; the use requires a type annotation or a future explicit rank
modifier.
Shape unification is deliberately restricted to this prefix-frame/suffix-cell normal form. Essential Arra does not require general associative word-equation unification over shape expressions.
The frame/cell rule is available to user-defined iter hooks. 'map is not a
compiler-only exception.
A dynamic rank-one array a[_] has a runtime length but does not expose a name
for that length. It is the non-dependent convenience form.
When later code must relate the runtime length to another type, the dimension is packaged existentially:
∃(m : Nat) a[m]
The runtime representation is (m, array). Elimination binds the dimension and
the array:
value (
(m, xs) → body
)
where m : Nat and xs : a[m] in body.
Nat is a value type distinct from I64; Core natural values are unbounded.
Integer literals remain I64. The Prelude exports explicit checked
i64ToNat : I64 →⟪() Fail⟫ Nat and
natToI64 : Nat →⟪() Fail⟫ I64 functions. Negative I64 values and natural
values outside the I64 range take the declared Fail path. Array lengths,
indices, updates, generated indices, and existential witnesses use Nat.
When an expected type is ∃(m : Nat) body, a compatible expression may be
packaged contextually at an annotation, function argument or result, or nested
structural position. The carrier dimension must be recoverable from the value;
it may not escape through the expression’s effect row. Packaging evaluates the
source expression once.
No solver is required to introduce, package, or eliminate an existential dimension. Essential filtering can therefore retain its output shape:
iter ⟦a[n]⟧ 'filter (a → Bool) → ∃(m : Nat) a[m]
A future extension may refine this to:
∃(m : Nat, m ≤ n) a[m]
but the inequality and its proof are outside the kernel.
Existentials also preserve unaffected axes. Filtering matrix rows can return:
∃(k : Nat) a[k;m]
rather than erasing the entire result to an unknown-rank array.
An iter projection first attempts ordinary hook resolution against an
existential subject as a whole. A matching direct hook wins. If none matches,
the elaborator may open exactly one outer package, retry the same iter family
once against its body, and then close the scope. It repackages the opened
dimension exactly when that dimension occurs in the traversal result type;
otherwise it eliminates the witness. A dimension in the escaping effect row is
rejected. The rule does not recurse and does not apply to gen, ordinary
application, operators, projection, assignment, to, nested packages, or
multiple existential operands.
The package-producing subject, traversal operand, selected traversal, and optional repackaging each evaluate at most once. Opening and repackaging are pure; callback effects retain their ordinary left-to-right order.
flatMapRegular arrays require every cell at a given level to have the same shape. Essential Arra does not expose unrestricted irregular nested arrays.
Ordinary 'map therefore requires a uniform output shape. A mapper returning a
different length for each input cell uses 'flatMap, which exposes irregularity
through a flat value array and segment metadata.
Following Futhark’s flatmap design, the general kernel signature is:
iter ∀ (e : Effects) (frame : Shape) (cell : Shape) a b c
⇒ 'flatMap (a[cell] →⟪e⟫ ∃(k : Nat) (b[k], c))
: a[frame; cell] →⟪e⟫ ∃(m : Nat) {
lengths: Nat[frame],
values: b[m],
uniform: c[frame]
}
For each frame position:
lengths records the length of that invocation’s variable-sized result.values contains all result segments concatenated in LTR frame order.uniform contains one fixed-shape side result from each invocation.m is the total length of values.Callers that do not need uniform may discard that field after opening the
existential result. The initial Prelude does not export a separate
'flatMapValues wrapper.
The runtime constructor maintains the invariant:
m = sum(lengths)
lengths is the semantic segment descriptor. Following the representation
discipline used by
Futhark’s full flattening,
an optimizing pass may internally derive flags, offsets, element-to-segment
indices, or other redundant metadata, but these are not source-level layouts.
Essential Arra does not require Z3 to prove the length relation. The treewalk
backend evaluates each cell sequentially, records its length, and concatenates
its values. Parallel flattening is a later transformation and does not alter
these semantics.
Rank polymorphism and irregularity are orthogonal:
'map.'flatMap.Segmented columnar records remain columnar. If b is a transparent record,
values : b[m] uses the same struct-of-arrays representation defined in §4.1.
Arra deliberately covers some computations at two scales. The typed functional layer defines scalar reference semantics: composition, ordered conditional choice, evidence flow, failure, and effects. The array layer is the preferred bulk vocabulary: vector operations, masks, selection, compaction, partitioning, reduction, and segmentation.
The intended idioms are:
| Problem scale | Primary expression |
|---|---|
| one value or one control decision | UCS conditional function |
| uniform work over cells | iter, such as 'map or 'fold |
| choose between already computed arrays | Boolean mask and selection |
| retain or divide cells | filtering, compaction, or partitioning |
| variable output cardinality | segmented 'flatMap |
| heterogeneous scalar result | algebraic data and postfix patterns |
| effectful choice | UCS inside deterministic traversal |
This overlap does not create two semantics. A clause list receiving an array tests that array as one value; it never silently becomes a pointwise conditional. Pointwise scalar control requires an explicit traversal. Masks are ordinary bulk values and standard array operations, not a replacement control language or additional Core dispatch family.
An optimizer may turn a pure, total UCS conditional inside a traversal into predication, mask selection, branch packing, or partitioned execution. The transformation must preserve which source expressions execute. It may not eagerly evaluate an untaken arm that can fail, perform an effect, diverge, or perform avoidable expensive work. Ordered effectful traversal remains the reference behavior when equivalence is not established.
Similarly, an optimized array of algebraic values may use a tag array plus payload columns. That is a future representation choice analogous to SoA, not an Essential source distinction. Pattern matching remains the reference semantics and may compile to tag masks and payload projection.
The standard library should prefer the array vocabulary for bulk programs rather than duplicate every mask, selection, or compaction operation with an ADT-heavy idiom. Both vocabularies still lower through the same checked Core; there is no separate scalar or array executor.
The source Prelude exposes a small leading-axis vocabulary:
length : ∀ (n : Nat) a ⇒ a[n] → Nat
reverse : ∀ (n : Nat) a ⇒ a[n] → a[n]
enumerate : ∀ (n : Nat) a ⇒ a[n] → (Nat, a)[n]
concat : ∀ a ⇒ ⟦a[_]; a[_]⟧ → ∃(n : Nat) a[n]
take : ∀ a ⇒ ⟦a[_]; Nat⟧ → ∃(n : Nat) a[n]
drop : ∀ a ⇒ ⟦a[_]; Nat⟧ → ∃(n : Nat) a[n]
zip : ∀ a b ⇒
⟦a[_]; b[_]⟧
→⟪LengthMismatch Fail⟫
∃(n : Nat) (a, b)[n]
adjacentPairs : ∀ a ⇒ a[_] → ∃(n : Nat) (a, a)[n]
Every operation uses the leading axis. reverse and enumerate preserve its
exact dimension. concat returns the sum of the two leading lengths. take
and drop clamp their Nat count to the input length. zip never truncates:
unequal lengths raise {left: Nat, right: Nat} LengthMismatch; equal lengths
preserve pairwise left-to-right order. adjacentPairs returns consecutive
overlapping pairs and has length max(input length - 1, 0).
The nominal values sum, product, any, and all are callable aggregate
markers selected through ordinary app hooks. sum and product support
I64, F64, and Nat arrays with additive and multiplicative identities.
any and all support Boolean arrays, inspect cells left-to-right, and may
short-circuit. Their empty identities are False and True.
Size-changing operations package their result dimension existentially rather than claiming a static relationship the current shape language cannot express. Array-producing operations preserve regularity and the canonical dense character and columnar-record representations. These mappings introduce no parallel dispatch mechanism: public combinations live in Prelude, while only irreducible traversal, allocation, and short-circuit boundaries are Core primitives.
I64 is a signed 64-bit two’s-complement value with the inclusive range
-2^63 through 2^63 - 1. Integer literals outside that range are rejected.
Default addition, subtraction, multiplication, and negation compute modulo
2^64, then interpret the result as signed. They are total and pure.
Comparison uses signed order.
Integer division reports () Fail exactly when its divisor is zero. Quotients
truncate toward zero. The otherwise overflowing case -2^63 / -1 produces
-2^63, consistently with modular negation. These rules are language semantics
and must not depend on host-language overflow behavior.
Nat is arbitrary precision. Natural addition and multiplication are total and
pure. Natural subtraction reports () Fail when its mathematical result would
be negative. i64ToNat reports () Fail for a negative argument; natToI64
reports () Fail for a value greater than 2^63 - 1.
F64 is IEEE 754 binary64. Its arithmetic, division, ordering, negation, and
sqrt preserve IEEE NaN, infinity, and signed-zero behavior; division by zero
and square root of a negative value produce their IEEE results rather than
Fail. op = uses the total runtime equality described above. Numeric
aggregation remains strict left-to-right and is never reassociated merely
because it is pure.
Overflow-sensitive fixed-width arithmetic is explicit and value-oriented.
checkedAdd, checkedSub, and checkedMul return I64 Option.
saturatingAdd remains pure and names saturation in the operation. Ordinary
arithmetic never acquires an implicit overflow effect.
Map is an opaque insertion-ordered source-library type. empty, singleton,
and fromEntries require a key Equality model and store the selected equality
mapping as ordinary executable data. fromEntries reports both equivalent keys
and their indices in DuplicateKey; it never silently overwrites. entries,
keys, and values preserve insertion order. put retains the original stored
key when updating an equivalent key and appends new keys. remove preserves the
remaining order. replaceKey substitutes the supplied equivalent
representative and returns None when no equivalent key exists.
Seq is an opaque pure lazy sequence with a pull returning Option (value,
tail). It is replayable, non-memoizing, and potentially infinite. 'generate,
array/List elements, characters, bytes, lines, 'map, 'filter, take,
and drop are lazy; callbacks retained by lazy transformations are pure.
Array/List elements constructs a constant-time view without copying elements.
'fold, 'find, any, all, and collect consume immediately, and effectful
terminal callbacks execute in pull order. collect materializes an
existentially sized regular array.
String sequence views retain the source String and byte offsets rather than
materializing intermediate arrays. lines recognizes LF and CRLF, excludes the
terminator, preserves interior empty lines, emits no extra empty line after a
final terminator, and yields a final unterminated line. Effectful,
resource-owning, memoized, parallel, or one-shot streams require distinct future
types; they are not modes of Seq.
Values have ordinary types; expressions have computation judgments:
value type: A
computation judgment: Γ ⊢ e : A ! ε
function type: A → (B ! ε)
surface function type: A →⟪ε⟫ B
Constructing a function is pure. Its arrow records the latent effect of calling
it. a → b is pure and a →⟪e⟫ b is effectful. The Unicode effect row or
ASCII <<...>> must attach directly to the arrow token; a -><<e>> b is valid
and a -> <<e>> b is not. At value level << and >> remain ordinary
operators.
A normalized row contains distinct instantiated nominal labels and at most one open tail:
preserve : ∀ (e : Effects) a b ⇒ (a →⟪e⟫ b) → a →⟪e⟫ b
withIO : ∀ (e : Effects) a b ⇒ (a →⟪e⟫ b) → a →⟪IO | e⟫ b
Known-prefix extension excludes duplicate labels. Rows are unordered upper bounds; strict lowering, not row order, fixes the runtime trace.
Application evaluates source expressions once in written order and unions their effects with the selected mapping’s latent effect. A centered mapping expression must be pure. Invocation positions evaluate left-to-right, followed by dynamic formation operands. An eager binding runs its initializer once; later reads are pure and do not replay initializer effects.
The source language declares non-resumable effects with bare operation signatures:
effect e Fail
raise : e
effect IO ()
Operation-free marker effects are valid. An operation has bottom result and may therefore inhabit any demanded result. A handler names and discharges one exact instantiated effect:
computation 'handle E Fail
raise error → error Err
return value → value Ok
The handler covers every operation exactly once and contains one return clause.
Operation and return-clause effects escape outside the handled computation.
Handling I64 Signal never removes String Signal.
IO is an ordinary operation-free nominal source effect backed by runtime
primitives. Source handlers require at least one control clause, so they cannot
discharge IO. Resumable operations, continuation binders, State, Nondet,
and multi-shot control remain outside Essential Arra.
Traversal propagates callback effects. Pure traversals may later fuse or run in parallel; effectful traversals execute sequentially in left-to-right frame or pull order. Effects never influence hook or model selection.
Each file declares one dotted module whose path matches its source path. A module contains an optional interface followed by an optional implementation, with at least one present:
Dependencies have separate semantics:
import M as X provides qualified access only;open M is implementation-only and adds an unqualified view;export M is interface-only and forwards a view.open and export accept exposing or except filters. Selectors cover
values, types, constructors, effects and operations, theories, entire model
groups, exact models, hook families, and exact hooks. Aliases rekey selected
names or hook selectors. import may alias its module but has no selector list.
Names introduced by the interface, including imported module aliases, flow forward into the implementation. Implementation declarations do not retroactively enter interface scope.
A module export is semantic closure: dependencies needed to understand its public declarations are retained even when not textually re-exported. A qualified hook request sees exactly that closed exported view and never the caller’s local candidates.
All source and installed Prelude modules share one dependency and initialization graph. Cycles reject. Bindings initialize eagerly once in deterministic dependency/source order. Imported libraries must initialize purely; the root may initialize effectfully, and its total initialization effect includes every eager root initializer.
Prelude.arra is an interface-only facade forwarding Prelude.Core,
Prelude.Numeric, Prelude.Text, Prelude.Array, Prelude.IO, Prelude.Map,
and Prelude.Seq. Only this facade is implicitly opened. Primitive names are
available only inside the installed Prelude graph.
Nested and parameterized modules are absent. Modules are coherence and initialization units, not optimization barriers.
The post-elaboration Core contains:
Literal Variable Lambda Apply
Let LetRec Constructor Case
Record Concat Remove Array
Project Update ArrayGet ArrayFilter
ArrayFlatten Unfold GenerateExact
View PackDim UnpackDim Perform
Handle Primitive
Tuple and unit values are records; Core has no tuple-specific nodes. View is a
checked representation-preserving adaptation used for nominal and distinct
values, dynamic dimensions, and column-backed logical record rows. Array filter,
segmented flatten, unfold, and exact generation retain distinct operational
boundaries.
Core types contain I64, Nat, U8, F64, Bool, Char, String,
Symbol, bottom, generic variables, nominal types, functions, structural
records, arrays, existentials, type constructors, and constructor application.
Every expression carries independently checked type and effect metadata.
Before Core:
Nat, Shape, Name, and Fields binders specialize,
while existential Nat witnesses become explicit runtime dimension evidence;The immutable monomorphic Typed IR lowers into Core. An independent Core checker
revalidates scopes, types, effects, patterns, shapes, layouts, primitive ABI,
and the bottom result of every Perform node. The deterministic treewalk
defines reference execution; optimizing backends are not required for language
correctness.
The following remain compatible extensions rather than partially accepted surface constructs.
Type → Type;iso declaration sugar and optimizer-facing derived views;Frame.unit and Frame.nesting
rewrites;These features must justify themselves against the complete working semantic kernel rather than serving as prerequisites for it.
An Essential Arra implementation is conforming only when it supports the end-to-end behavior specified here:
fun families, named pattern extraction, record
projection/assignment, rank traversal, output generation, and one-step
conversion.Type, Type → Type, Nat, Shape, Effects, Name, and Fields
quantification; extensible rows, disjoint sums, computed fields, and
parameterized nominal records.Char/U8 literals, explicit scalar and UTF-8 conversions,
checked numeric boundaries, ordered maps, and pure lazy sequences.The reference implementation satisfies this surface. A backend may optimize its representations or execution only where observable evaluation order, effects, failures, shapes, nominal boundaries, and module closure remain unchanged.
Essential Arra remains unmistakably Arra:
The larger language can grow around this kernel. The kernel must remain usable, explainable, independently executable, and structurally stable as those extensions arrive.