Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

lib/array.x

Dynamic contiguous arrays of Var elements.

Primary API

FunctionSummary
Array.concatReturns a fresh array holding a followed by b.
Array.containsReports whether a native element equals value.
Array.copyReturns a fresh packed copy, or NULL for a null array.
Array.countReturns how many native elements equal value.
Array.findReturns the first index whose native element equals value, or -1.
Array.foldlFolds fn over array from seed, front to back.
Array.freeReleases the Array and its backing storage, invalidating every alias.
Array.getindexReads index from a non-null array, counting negatives from the end.
Array.getsliceReturns a fresh packed array for normalized [start:end:step].
Array.indexofReturns the same first-match index as Array.find.
Array.insertInserts value at normalized index and returns it.
Array.iterInitializes dest to lazily yield boxed elements in index order.
Array.joinJoins the elements of array into one String separated by separator.
Array.mapReturns a new Array holding func applied to each element of array.
Array.map2Maps func over corresponding elements up to the shorter Array.
Array.newReturns a fresh empty packed array owned by the current Scope.
Array.postfixindexApplies postfix Array element increment or decrement.
Array.pushAppends value and returns it.
Array.removeRemoves and returns the element at normalized index.
Array.resizeResizes arr, truncating or appending Null elements as needed.
Array.reverseReverses array in place and returns that same array.
Array.setindexStores and returns value, counting negatives from the end.
Array.setsliceReplaces the region array[start:end] and returns array.
Array.shiftRemoves and returns the first element, shifting the remainder left.
Array.sortSorts array in place in ascending order and returns that same Array.
Array.sort_byStably sorts array by keys produced once per value, returning the Array.
Array.sort_withStably sorts array with a borrowed synchronous comparator and returns it.
Array.spliceReplaces remove_count values at normalized index and returns them.
Array.take_lastRemoves and returns the last element.
Array.try_nextWrites the next native element, advances cursor, and returns one.
Array.try_take_lastRemoves the last element into out and returns one when present.
Array.unshiftInserts value at the front and returns it, shifting elements right.
Array.updateindexUpdates one boxed element while preserving its Var tag.
Array.write_strAppends the packed-Array display text to out.
Block.arrayReturns the same object as an Array view; mutations remain shared.
Iter.arrayDrains iter into a fresh Array.

Array

Array.concat

Array Array.concat(Array a, Array b)

Returns a fresh array holding a followed by b. Neither input is modified. A null a returns NULL, while a null b produces an independent copy of a.

Raises: <size-limit> or <alloc-fail> when the result cannot be represented or allocated.

Source: lib/array.x:72

Array.contains

int Array.contains(Array array, Var value)

Reports whether a native element equals value. The scan is linear. Raises: <size-limit> when the length exceeds the integer index domain.

Source: lib/array.x:72

Array.copy

Array Array.copy(Array array)

Returns a fresh packed copy, or NULL for a null array. The result has independent mutable storage containing the same stored values.

Raises: <size-limit> or <alloc-fail> when the copy cannot be represented or allocated.

Source: lib/array.x:72

Array.count

int Array.count(Array array, Var value)

Returns how many native elements equal value. A null array returns zero; the scan is linear.

Raises: <size-limit> when the length exceeds the integer index domain.

Source: lib/array.x:72

Array.find

int Array.find(Array array, Var value)

Returns the first index whose native element equals value, or -1. A null array returns -1; the scan is linear and preserves source order.

Raises: <size-limit> when the length exceeds the integer index domain.

Source: lib/array.x:72

Array.foldl

Var Array.foldl(Array array, Var seed, Func fn)

Folds fn over array from seed, front to back. A void seed means “no seed”: the first element becomes the accumulator and the fold starts at the second, so folding an empty Array that way returns void. Elements are passed as values. Input with nothing left to fold does not invoke or check fn. The callback receives the accumulator then the next element and is not retained. It must not structurally mutate array during the walk. Any cause from Func.apply or fn propagates without changing array.

Source: lib/array.x:227

Array.free

void Array.free(Array a0)

Releases the Array and its backing storage, invalidating every alias. The Block protocol generates the definition.

Source: lib/array.x:119

Array.getindex

Var Array.getindex(Array array, int index)

Reads index from a non-null array, counting negatives from the end. Returns void when the normalized index is outside the array.

Raises: <size-limit> outside the integer index domain.

Source: lib/array.x:91

Array.getslice

Array Array.getslice(Array array, int start, int end, int step)

Returns a fresh packed array for normalized [start:end:step]. Negative bounds count from the end and a negative step walks backward.

Raises: <bad-arg> for a null array or zero step, <size-limit> outside the integer index domain, or <alloc-fail> on allocation failure.

Source: lib/array.x:72

Array.indexof

int Array.indexof(Array array, Var value)

Returns the same first-match index as Array.find.

Source: lib/array.x:72

Array.insert

Var Array.insert(Array array, int index, Var value)

Inserts value at normalized index and returns it. The accepted range includes the position after the last element; negative indices are normalized against that wider range. Boxed Array returns void for a null array or out-of-range index without mutation.

Raises: <bad-arg> for a null typed array or out-of-range typed-array index, <size-limit> at the integer index limit, or <alloc-fail> when storage cannot grow.

Source: lib/array.x:72

Array.iter

Iter Array.iter(Array array, Iter dest)

Initializes dest to lazily yield boxed elements in index order. Returns dest, whose storage is caller-owned. The iterator borrows array and reads its current storage on each step, so both must remain live and mutation can change the remaining traversal. A null dest returns NULL. A null array, or one longer than the integer index domain, is exhausted. A boxed wide element is Scope-owned; retaining one after a pull requires its owning Scope to remain live.

Raises: any cause from boxing an element.

Source: lib/array.x:240

Array.join

meta native String Array.join(Array array, String separator)

Joins the elements of array into one String separated by separator. Elements are converted with their str form, so a String element contributes its bytes without quotes and a number contributes its digits. A null separator joins with nothing between elements, and an empty array yields the empty String.

The receiver here is the Array. In String.join the separator is the receiver and the elements arrive as a List. Raises: <alloc-fail> or <size-limit> while rendering or canonicalizing the result, or a cause from an element’s write_str.

Source: lib/array.x:439

Array.map

Array Array.map(Array array, Func func)

Returns a new Array holding func applied to each element of array. array itself is untouched, and elements are passed as values. An empty input returns a fresh empty Array without invoking or checking func. The callback is invoked front to back and is not retained. It must not mutate array while the walk is in progress; Func rejects a void result.

Raises: whatever Func.apply or func raises, or an allocation cause while constructing the result. The partial result is freed.

Source: lib/array.x:196

Array.map2

Array Array.map2(Array a, Array b, Func func)

Maps func over corresponding elements up to the shorter Array. The callback receives left then right, runs front to back, and is not retained. An empty input does not invoke or check it; neither input may be structurally mutated during the walk.

Raises: whatever Func.apply or func raises, or an allocation cause while constructing the result. The partial result is freed.

Source: lib/array.x:210

Array.new

Array Array.new(void)

Returns a fresh empty packed array owned by the current Scope.

Raises: <alloc-fail> when storage cannot be allocated.

Source: lib/array.x:72

Array.postfixindex

Var Array.postfixindex(Array array, int index, Symbol op)

Applies postfix Array element increment or decrement. The returned value is the original element. The slot remains unchanged if the index or operation is invalid.

Raises: <bad-arg> for a null Array or invalid index, <size-limit> when its length cannot be indexed, or any cause from Var.postfix. The element is unchanged on failure.

Source: lib/array.x:177

Array.push

Var Array.push(Array array, Var value)

Appends value and returns it. Boxed Array returns void for a null array.

Raises: <bad-arg> for a null typed array, <size-limit> at the integer index limit, or <alloc-fail> when storage cannot grow.

Source: lib/array.x:72

Array.remove

Var Array.remove(Array array, int index)

Removes and returns the element at normalized index. Negative indices count from the end; following elements shift left. Boxed Array returns void for a null array or out-of-range index.

Raises: <bad-arg> for a null typed array or out-of-range typed-array index, or <size-limit> when the length exceeds the integer index domain in either family.

Source: lib/array.x:72

Array.resize

meta native void Array.resize(Array arr, size_t size)

Resizes arr, truncating or appending Null elements as needed.

Raises: <size-limit> when size exceeds the Array index domain, plus any cause from Block growth. Allocation and size failure do not return here. A growth failure leaves the length and existing elements unchanged.

Source: lib/array.x:126

Array.reverse

Array Array.reverse(Array array)

Reverses array in place and returns that same array. A null or one-element array is returned unchanged.

Source: lib/array.x:72

Array.setindex

Var Array.setindex(Array array, int index, Var value)

Stores and returns value, counting negatives from the end. Requires a non-null array. Returns void for an out-of-range index.

Raises: <size-limit> outside the index domain or <void-op> when storing void at a valid index.

Source: lib/array.x:103

Array.setslice

Array Array.setslice(Array array, int start, int end, Array values)

Replaces the region array[start:end] and returns array. Bounds normalize as slice bounds, so a negative end is a stop. Reversed bounds are swapped; null values deletes the region. Passing array itself as values is supported and copies before mutation.

Raises: <bad-arg> for a null array, <size-limit> outside the integer index domain, or <alloc-fail> while copying self-aliased values or growing storage for the replacement. These failures leave array unchanged.

Source: lib/array.x:72

Array.shift

Var Array.shift(Array array)

Removes and returns the first element, shifting the remainder left. This operation is O(n). Boxed Array returns void for a null or empty array.

Raises: <bad-arg> for a null or empty typed array, or <size-limit> when the length exceeds the integer index domain in either family.

Source: lib/array.x:72

Array.sort

meta native Self Array.sort(Self array)

Sorts array in place in ascending order and returns that same Array. Call Array.copy first to preserve the original order. Ordering is Var.compare, which compares numbers numerically and Strings, Symbols, and Atoms by content. The sort is qsort, so it is not stable, and a null or one-element array is returned unchanged.

Array numbers = [5, 3, 9, 1];
Array sorted = numbers.sort();
printf("%s %d\n", numbers.repr(), sorted == numbers);

Raises: causes from element comparison. The Array may already be partially reordered when a catch receives the cause.

Source: lib/array.x:261

Array.sort_by

Self Array.sort_by(Self array, Func key)

Stably sorts array by keys produced once per value, returning the Array. The borrowed callback runs front to back and must not mutate this Array. Keys use Var.compare; equal keys preserve the original element order. A null or empty Array invokes no callback. Sorting another Array inside the callback is valid. Raises: allocation, key comparison, Func.apply, or callback causes. Failure leaves the original Array unchanged; callback side effects are not undone.

Source: lib/array.x:325

Array.sort_with

Self Array.sort_with(Self array, Func compare)

Stably sorts array with a borrowed synchronous comparator and returns it. The callback receives two values; its result converts to int, with a negative, zero, or positive result ordering the first before, equal to, or after the second. It must give a consistent ordering and must not mutate this Array. Sorting a different Array inside the callback is valid. Null and fewer than two elements return unchanged without a callback.

Raises: allocation, Func.apply, conversion, or callback causes. Failure leaves the original Array unchanged; temporary storage is released. Callback side effects are not undone.

Source: lib/array.x:280

Array.splice

Array Array.splice(Array array, int index, int remove_count, Array values)

Replaces remove_count values at normalized index and returns them. The result is a fresh packed array. A nonpositive count removes nothing; null values performs deletion, and self-splicing is supported.

Raises: <bad-arg> for a null array, <size-limit> outside the integer index domain, or <alloc-fail> on allocation failure.

Source: lib/array.x:72

Array.take_last

Var Array.take_last(Array array)

Removes and returns the last element. Boxed Array returns void for a null or empty array.

Raises: <bad-arg> for a null or empty typed array.

Source: lib/array.x:72

Array.try_next

int Array.try_next(Array array, int &?cursor, Var &?out)

Writes the next native element, advances cursor, and returns one. Initialize the caller-owned cursor to zero. A null argument, negative cursor, exhaustion, or an array outside the integer index domain returns zero without changing cursor or out. Structural mutation invalidates the cursor.

Source: lib/array.x:72

Array.try_take_last

int Array.try_take_last(Array array, Var &?out)

Removes the last element into out and returns one when present. A null or empty array, or null out, returns zero without writing or changing the array.

Source: lib/array.x:72

Array.unshift

Var Array.unshift(Array array, Var value)

Inserts value at the front and returns it, shifting elements right. This operation is O(n). Boxed Array returns void for a null array.

Raises: <bad-arg> for a null typed array, <size-limit> at the integer index limit, or <alloc-fail> when storage cannot grow.

Source: lib/array.x:72

Array.updateindex

Var Array.updateindex(Array array, int index, Symbol op, Var rhs)

Updates one boxed element while preserving its Var tag.

Source: lib/array.x:157

Array.write_str

Buffer Array.write_str(Array array, Buffer out)

Appends the packed-Array display text to out.

Source: lib/array.x:239

Block

Block.array

inline Array Block.array(Block x)

Returns the same object as an Array view; mutations remain shared.

Source: lib/array.x:114

Iter

Iter.array

meta native Array Iter.array(Iter iter)

Drains iter into a fresh Array.

Source: lib/array.x:452

Advanced and interop API

FunctionSummary
Array.cleanupEnds the owned lifetime when a managed local leaves its block.
Array.compareCompares packed Arrays lexicographically with the element family’s ordering.
Array.equalReports elementwise native equality.
Array.heap_popRemoves and returns the smallest element of heap, or void when it is empty.
Array.heap_pushAdds val to heap, an Array maintained as a binary min-heap.
Array.heapifyRearranges heap in place so that it satisfies the min-heap invariant.
Array.remsliceRemoves the region array[start:end] and returns a fresh packed array.
Array.reprReturns the readable packed-Array representation.
Array.strReturns the packed-Array display String.
Array.update_nAppends exactly element_count variadic values to array.
Array.write_reprAppends the readable packed-Array representation to out.

Array

Array.cleanup

meta native void Array.cleanup(Array value)

Ends the owned lifetime when a managed local leaves its block.

Source: lib/array.x:460

Array.compare

int Array.compare(Array a, Array b)

Compares packed Arrays lexicographically with the element family’s ordering. Identical handles compare equal and NULL sorts first.

Source: lib/array.x:239

Array.equal

int Array.equal(Array a, Array b)

Reports elementwise native equality. Two null arrays compare equal; one null array or different lengths compare unequal.

Source: lib/array.x:72

Array.heap_pop

meta native Var Array.heap_pop(Array heap)

Removes and returns the smallest element of heap, or void when it is empty. The remaining elements are re-heaped in O(log n), so repeated calls yield ascending order and draining a heap is a sort. An Array that never satisfied the heap invariant gives a meaningless answer instead of an error. Call Array.heapify first if it was not built with Array.heap_push.

Raises: any cause reported by element comparison while restoring the heap. The heap may already have removed its root when a catch receives the error.

Source: lib/array.x:405

Array.heap_push

meta native void Array.heap_push(Array heap, Var val)

Adds val to heap, an Array maintained as a binary min-heap. The heap operations arrange an Array as a priority queue in place, with no second data structure and no extra allocation. The elements stay in the Array with the smallest at index 0. Ordering is Var.compare, the same rule Array.sort uses.

heap_push and Array.heap_pop maintain the invariant, but the positional operations do not. After a plain Array.push, an assignment through Array.setindex, or any slicing, call Array.heapify before popping again.

Array heap = [];
heap.heap_push(30);
heap.heap_push(10);
heap.heap_push(20);
printf("%s %s\n", heap.heap_pop().repr(), heap.heap_pop().repr());

Raises: <void-op> when val is void, or <size-limit> when the heap cannot grow within the Array index domain, <alloc-fail> when storage cannot grow, or a cause from element comparison. A value or earlier swap may remain when comparison fails; pre-insertion failures leave the heap unchanged.

Source: lib/array.x:390

Array.heapify

meta native void Array.heapify(Array heap)

Rearranges heap in place so that it satisfies the min-heap invariant. Use this before the first Array.heap_pop on an Array that was built by Array.push, read in from somewhere else, or disturbed by a positional operation. It is O(n), cheaper than pushing the same elements one at a time.

Raises: <size-limit> when heap exceeds the INT_MAX index limit that Array.getindex describes, or a cause from element comparison. Comparison failure may leave a partially rearranged Array.

Source: lib/array.x:424

Array.remslice

Array Array.remslice(Array array, int start, int end)

Removes the region array[start:end] and returns a fresh packed array. Bounds normalize as slice bounds, so a negative end is a stop. Reversed bounds are swapped, and the removed values retain their order.

Raises: <bad-arg> for a null array, <size-limit> outside the integer index domain, or <alloc-fail> on allocation failure.

Source: lib/array.x:72

Array.repr

String Array.repr(Array array)

Returns the readable packed-Array representation.

Source: lib/array.x:239

Array.str

String Array.str(Array array)

Returns the packed-Array display String.

Source: lib/array.x:239

Array.update_n

Self Array.update_n(Self array, unsigned element_count, ...)

Appends exactly element_count variadic values to array. Values appended before a later <void-op>, <size-limit>, or <alloc-fail> remain in array. The caller must supply that many Var arguments.

Source: lib/array.x:145

Array.write_repr

Buffer Array.write_repr(Array array, Buffer out)

Appends the readable packed-Array representation to out.

Source: lib/array.x:239

Runtime-internal callables

These callables connect runtime translation units. They are documented for source readers but are not supported as user API.

FunctionSummary
Array.blockReturns the same object as a Block view; no copy or transfer occurs.

Array

Array.block

inline Block Array.block(Array x)

Returns the same object as a Block view; no copy or transfer occurs.

Source: lib/array.x:112

Public types

TypeKindSummary
ArrayaliasHolds a mutable identity-bearing sequence of non-void Var elements.

Array

typedef Block Array

Holds a mutable identity-bearing sequence of non-void Var elements. Array is the same object as its Block view; that object and its backing storage belong to the Scope active at construction. Assignment aliases it; Array.copy creates a new container, but still borrows any objects referenced by its elements. Array.free invalidates all aliases.

Source: lib/array.x:36

Design notes

Array is mutable, identity-bearing contiguous Var storage over Block. Every constructor returns an allocated object, including for an empty Array; assignment aliases that object, while Array.copy makes a shallow independent container. Scope owns its allocation unless Array.free shortens the lifetime. Array data may contain raw Null but never void.

The declared Block protocol supplies Array’s generated truth, pop, free, and truncate members. Array.pop discards the final element; Array.take_last removes and returns it.

Indexing and slicing normalize negative positions here. Positional mutation preserves the object identity, and structural mutation invalidates outstanding iterators.

Tests and examples

make verify (unittest/test-array.x) and make examples.