Browse documentation
Data structures

Array

Fixed length typed storage, mutation, sorting, searching, numerical operations, and time and space complexity.

Implemented

Integer, binary floating and Decimal buffers support explicit immutable snapshots for sharing local repetition inputs. See FrozenArray ownership, methods, and accounting.

parallel.repeat can allocate typed output buffers and lend each task a disjoint OutputRegion<T> locally or on enrolled CPU cluster workers. Successful calls return immutable OutputResults<T>, which can be reused directly as later repetition inputs without local payload copies. See typed output regions.

The numeric APIs below require a compatible runtime with fixed width integer and Float32 packed storage, checked conversions and Float32/Float64 Tensor bridges that preserve dtype. Device and module requirements are documented with their APIs.

Array<T> is a built in, fixed length, one dimensional data structure with an explicit scalar element type. Construction initializes every element. Indexed mutation is permitted; length and capacity remain fixed. Primitive elements require no import; unit element types require aner.units.

Construction

aner
let scores = Array<Int64>(size: 4, fill: 0)
scores.set(index: 0, value: 30)
scores.set(1, 10)
scores.set(2, 20)
scores.sort()
print(scores.to_list())
print(scores.find(20))

The output is List(0, 10, 20, 30), followed by 2. Constructor arguments are size: Int64 and fill: T. Size must be between 0 and 10,000,000 inclusive. Empty arrays are valid. capacity() always equals len().

The primitive element type is any 8/16/32/64-bit signed or unsigned integer, Float32, Float64, Decimal, Bool, or String; unit specializations below also admit Quantity<UnitCode> and Point<UnitCode>. Type arguments are required. Array<Number>, Array<Any>, nullable elements, nested arrays, and user object element types are unsupported. Scalar arguments at Float64 boundaries admit checked exact integer to Float64 promotion, including numeric Number values; inexact integer promotion fails with R1003 and requires an explicit Float64(value) to permit rounding. Concrete integer scalar inputs use checked exact conversions into the element dtype, including narrowing and signedness changes; out of range values fail with R1003 before writing. Statically Number, Float32, or Float64 inputs require an explicit integer constructor. Float32 cells accept implicit numeric conversions only when exactly representable; use Float32(value) explicitly to permit rounding. Bool is a separate type. Float32/Float64 elements and computed array results must be finite.

aner
let values = Array<Float64>(size: 3, fill: 0.0)
values.set(0, Float64(2))

Checked bracket access and numeric updates

Bracket syntax requires Aner 0.0.4 or newer. The opening [ must be on the same physical line as the receiver's final token; coordinate expressions inside the brackets can span lines. The existing get(index) and set(index, value) methods retain their contracts.

aner
let values = Array<Float64>(size: 3, fill: 0.0)
values[0] = 3.0
values[1] = 4.0
values[1] += 2.0
print(values[0])
print(values[1])
print(values.get(1))

This complete program prints 3.0, 6.0, then 6.0. values[index] reads T and values[index] = value writes T, with checked exact integer to integer conversions and exact numeric promotion for floating cells. The coordinate must be a nonnegative in range Int64; negative wrapping, clamping and slice syntax are unsupported. Bool/String arrays permit same type get/set; primitive numeric compound updates +=, -=, *= and /= follow numeric promotion and require a result compatible with the cell type. Integer and Float32 cells reject /= because / now returns Float64. Unit cells use scalar unit arithmetic and require the final exact element type, as described in unit arrays. %= and String/Bool compound updates are unsupported.

The receiver and coordinate evaluate once. An assignment validates the address before evaluating its right side. A compound update also reads the prior element before right side effects, then computes and performs a checked write. Integer arithmetic retains overflow checks; Float64 array results must remain finite. Completed right side effects are not rolled back if calculation or final mutation fails. A let binding permits these writes under the existing mutable buffer contract.

The same one coordinate syntax works for DynamicArray. NDArray uses one coordinate per runtime axis, as described in multidimensional bracket access. String, Dictionary, List and Tensor use their existing accessor APIs; their bracket syntax is unsupported.

Decimal element arguments accept Decimal and lossless concrete integer inputs. Binary floating inputs are rejected; construct Decimal from original text or direct source literals before storage. Decimal arithmetic, sum, mean and extrema retain Decimal, using the fixed 34 digit half even policy; dot and cumulative sums follow that same policy. Decimal variance and standard deviation are unavailable. Integer arrays convert exactly with .astype("Decimal"); the same target copies Decimal arrays. Binary floating arrays cannot convert to Decimal. .to_float() and .astype("Float64") explicitly permit rounding and underflow to zero in an independent buffer; finite overflow fails. Decimal .astype("Float32") and direct Tensor bridges remain unsupported. .snapshot() creates an immutable FrozenArray; Decimal scalars, snapshots and typed outputs retain exact values in supported parallel transport. See Decimal arrays and CSV.

Elements with physical units

Aner 0.0.4 or newer also supports Quantity<UnitCode> and Point<UnitCode> elements after import aner.units. For example, Array<Quantity<m>> stores contiguous Float64 magnitudes with one immutable meter descriptor. Writes require the exact element type; explicitly convert another compatible unit before storage.

The unit array guide defines unit preserving arithmetic, Point means and interval standard deviations, literal .to(...) conversion and explicit .values() removal. Direct unit array .to_float() and .to_tensor() are unavailable. Existing ownership and container limits still apply; no measurement uncertainty or coordinate identity is inferred.

Storage and ownership

Integer elements occupy contiguous 1/2/4/8-byte native slots according to the declared width; Float32 occupies four bytes, Float64 eight, and Bool one byte per element. Decimal uses contiguous immutable value handles and a conservative logical charge for each bounded coefficient. These counts exclude container metadata and allocator overhead. Scalars and mixed List values keep their tagged runtime representation, regardless of integer width. String elements use contiguous native descriptors with separately owned text payloads; text is not stored as a packed character matrix. Elements do not carry individual Any tags.

A let binding prevents rebinding; it does not prevent element mutation. Assignment shares object identity and storage. copy() returns independent storage. slice(start, stop) returns an independent same type array for the half open interval; it is not a view. Equality compares object identity, not element contents.

aner
let original = Array<Int64>(size: 2, fill: 9)
let alias = original
let independent = original.copy()
alias.set(0, 3)
print(original.get(0))
print(independent.get(0))

The output is 3, then 9. Arrays may be held in Any, collection values, and user class fields. cast<Array<Int64>>(value) validates the family and exact element type, including any unit and quantity/point kind, without conversion or copying.

reshape(shape: List) produces a new NDArray descriptor sharing the fixed buffer. It preserves dtype and row major element order. The supplied shape must contain 1 to 8 Int64 dimensions from 0 through 10,000,000 with the same total element count; dimension inference is unavailable. Writes through either descriptor are visible through the other. Sorted search metadata remains correct after a shared buffer mutation.

Float32 sum, dot, and matrix products accumulate in Float64 before a checked rounded Float32 output; elementwise arithmetic and cumulative sums use Float32. For integer and binary floating arrays, mean, variance, and standard deviation return Float64. .astype("Float32") and .astype("Float64") explicitly convert integer/binary floating arrays into independent storage; the dtype must be a literal String. .to_float() still returns Float64. See Float32 for precision and overflow details.

Methods and complexity

Let n be the element count, m the length of a copied slice, and r the rank of a reshape result. Persistent scalar storage is O(n). The space column distinguishes additional auxiliary storage from newly allocated result storage. Empty input operations include constant work.

MethodResultTimeAdditional space
Array<T>(size: Int64, fill: T)Array<T>O(n)O(n) result
capacity(), len()Int64O(1)O(1)
contains(value: T)BoolO(log n) sorted; O(n) otherwiseO(1)
copy()Independent Array<T>O(n)O(n) result
fill(value: T)UnitO(n)O(1), subject to String qualification below
find(value: T)First matching Int64 index, or −1O(log n) sorted; O(n) otherwiseO(1)
get(index: Int64)TO(1)O(1), plus any returned String payload
is_empty(), is_sorted()BoolO(1)O(1)
reshape(shape: List)Shared NDArray<T> descriptorO(r)O(r) metadata; no element copy
reverse()UnitO(n)O(1)
set(index: Int64, value: T)UnitO(1)O(1), subject to String qualification
slice(start: Int64, stop: Int64)Independent Array<T>O(m)O(m) result
sort()UnitO(n log n), worst caseO(1)
to_list()Independent ListO(n)O(n) result

Length changing methods, including append, insert, remove_at, pop, resize, clear, and reserve, are unavailable and rejected during checking.

Sorting and searching

sort() applies in place, unstable heapsort in ascending order. All integer types, both binary floating types and Decimal use numerical order. Bool orders false before true. String uses case sensitive lexicographic order of encoded bytes, without locale rules, natural number order, or Unicode normalization. Positive and negative numerical zero compare equally. A custom comparator and descending parameter are unavailable.

The runtime maintains an exact count of adjacent inversions. is_sorted() therefore requires O(1) time; empty and singleton arrays are sorted. When the count is zero, find and contains use lower bound binary search. Otherwise they use linear search. No search tree is allocated. Mutations immediately update the search strategy. Duplicate values return the first matching index.

aner
let items = Array<Int64>(size: 3, fill: 0)
items.set(0, 30)
items.set(1, 10)
items.set(2, 20)
print(items.is_sorted())
print(items.find(20))
items.sort()
print(items.is_sorted())
print(items.find(20))

The output is false, 2, true, 1.

Numerical methods

The following table describes primitive integer, Float32/Float64 and Decimal numerical methods. Unit bearing specializations use the separate typed arithmetic and reduction contracts. Binary array operands require Array<T> with the same dtype and length. Arithmetic results are independent arrays; inputs remain unchanged.

MethodResultTimeAdditional space
add(other: Array<T>), sub(other: Array<T>), mul(other: Array<T>)Array<T>O(n)O(n) result
argmax(), argmin()First tied Int64 indexO(n)O(1)
cumsum()Array<T>O(n)O(n) result
div(other: Array<T>): Float32/Float64/Decimal onlyArray<T>O(n)O(n) result
dot(other: Array<T>)TO(n)O(1)
max(), min(), sum()TO(n)O(1)
mean()Decimal for Decimal elements; Float64 otherwiseO(n)O(1)
std(), variance(): integer/binary float onlyFloat64O(n)O(1)
scale(factor: T)Array<T>O(n)O(n) result
astype(dtype: String)Independent converted Array; literal dtype, subject to Decimal rules aboveO(n)O(n) result
Array.from_tensor<T>(tensor: Tensor): floating T onlyIndependent Array<T>; exact Tensor dtypeO(n)O(n) result, plus optional source host cache
to_float()Array<Float64>O(n)O(n) result
to_tensor(rows: Int64, cols: Int64): Float32/Float64 onlyDetached TensorO(n)O(n) result

Empty sum and dot return typed zero. Empty cumsum and elementwise operations are valid. Mean, standard deviation, variance, extrema, and their indices require nonempty input. Variance and standard deviation use the population definition, dividing by n; no sample statistic parameter is available.

Every integer intermediate is checked in the array's declared dtype, including sum/dot/cumsum and matrix products. Result arrays and scalar sum/dot/extrema retain that dtype. Overflow fails even if a later term could cancel it. Integer division is unavailable; Float32/Float64 division rejects zero divisors and nonfinite results. Decimal division follows the policy above. to_float() is explicit and detached; large integer values may round. Integer/binary floating means and population statistics return Float64 and may round. Integer means use exact wide accumulation before Float64 conversion; integer spread calculations preserve differences before conversion. Floating statistics use scaled computation to reduce avoidable overflow, subject to representable range and roundoff. A standard deviation can be representable while its variance is not.

Array.from_tensor<Float32>(tensor) and the Float64 specialization create independent detached packed copies and require an exact Tensor dtype match. Use Tensor .astype(...) explicitly to change dtype first. The result flattens row major values. GPU inputs may require host readback.

to_tensor requires positive dimensions whose product equals n. It preserves Float32 or Float64 dtype while copying values into a detached row major CPU Tensor; the source array does not record gradients. Inference of the bridge result needs no import. Explicit Tensor annotations and Tensor operations require the appropriate numerical module.

aner
let x = Array<Float64>(size: 3, fill: 0.0)
x.set(0, 1.0)
x.set(1, 2.0)
x.set(2, 3.0)
let y = x.scale(factor: 2.0)
print(x.sum())
print(x.dot(y))
print(x.cumsum().to_list())
let detached = x.to_tensor(rows: 1, cols: 3)

String complexity

Scalar complexity rows apply directly to every integer type, Float32, Float64, and Bool. String operations additionally account for bytes copied, released, or compared. Persistent String storage is O(n + B), where B is total owned text bytes. get returns an owned String copy and therefore includes its text length in time and result space. set, copy, slice, and conversions include copied payload bytes.

String fill constructs an entire replacement buffer before mutation: O(n + copied/released text bytes) time and O(n + new text bytes) temporary space. Searching performs O(log n) or O(n) comparisons; each comparison can inspect a common prefix. For maximum String length k, sorting has O(n log n · (1 + k)) worst case time and O(1) auxiliary descriptors.

Bounds and errors

Indices are zero based. get and set require 0 <= index < n; negative indices are unsupported. Slices require 0 <= start <= stop <= n.

Invalid size, out of bounds indices, nonfinite values, integer overflow, incompatible operands, invalid reshape, and array allocation quota exhaustion report source located R3001. Unsupported types, methods, and statically known dtype errors are detected before execution. Host allocation failure uses the CLI's E9003 insufficient memory handler. Failed native mutation does not partially change an existing array. A persistent session runtime error clears session state.

Each buffer permits at most 10,000,000 elements. The byte budget can impose a smaller effective limit for wider dtypes: ten million Int8 values occupy 10 MB of payload, while ten million Int64 values exceed the unchanged 64 MiB quota. Typed array buffers share a 64 MiB logical allocation budget in one heap, including capacity slots, String descriptors, and owned String payloads. Shared reshape buffers are charged once. The budget is separate from collection slots and Tensor limits, and excludes allocator overhead, transient replacement buffers, and total process memory. Unreachable buffers are reclaimed after successful persistent session cells; a retained reshape descriptor keeps its shared buffer alive.

Development inspection

Development observations show dtype, length, capacity, sorted status, and up to 16 copied elements. Production omits recording while preserving validation and algorithms. The report directory must be new:

sh
aner examples/arrays_basic.aner --dev artifacts/array-inspection

The array construction tutorial, numerical tutorial, VS Code array notebook, and Jupyter array notebook exercise the typed array APIs. The concise research syntax program combines brackets, numeric updates, defaults and Result propagation. Use aner check before execution when validating a source file.

  • DynamicArray: capacity managed typed sequences.
  • NDArray: fixed multidimensional shapes and broadcasting.
  • Tensor: numerical computation and differentiation.
  • Development mode: bounded reports and notebook inspection.
Aner documentation · Reference and guides