LEVIATHAN v962456e · 962456eee1

Standard Library

class Array<T>

An ordered sequence of values of one type, Array<T>, with value semantics.

since 0.1.0-alpha.1linuxwindowswasm

bases
IIterable<T>

Overview

An array is never changed in place. Every method that appears to change it (add, insertAt, sort, reverse, and so on) returns a new array and leaves the receiver untouched, so you rebind the result to keep it: a = a.add(4);. Assigning a[i] = v is shorthand for the same rebinding. Copying an array into another variable gives you an independent value.

Create an array with a literal such as [1, 2, 3], with Array() for an empty one, or with Array(n, fill) for n copies of one value. A declaration with no initializer, such as Array<int> a;, is the empty array. Indexes start at 0 and an index outside 0 .. length() - 1 throws a RuntimeException.

for (T x in a) visits the elements in order. Elements are compared with == by the searching methods (contains, indexOf, unique); the methods that take a function (where, map, reduce, ...) run it eagerly over every element, unlike the lazy Seq returned by asSeq.

Description

Array<T> is an ordered sequence of T with pure value semantics: no method changes the array it is called on. Every "changing" method (add, with, insertAt, removeAt, reverse, sort, map and the rest) returns a new array and leaves the receiver exactly as it was. To change a variable, rebind it: a = a.add(x). An index assignment a[i] = v is the same rebind in shorter form. Two names that start out sharing one array never affect each other. The shared rule for Array, Map and Set is described in lang.collection-value-semantics.

Rebinding is how an array changes

Array<int> a = [3, 1, 2];
Array<int> b = a.add(4);
console.writeln(a);
console.writeln(b);
a.add(99);
console.writeln(a);
a = a.add(10);
console.writeln(a);
Array<int> c = a;
c[0] = 77;
console.writeln(a);
console.writeln(c);
[3, 1, 2]
[3, 1, 2, 4]
[3, 1, 2]
[3, 1, 2, 10]
[3, 1, 2, 10]
[77, 1, 2, 10]

The statement a.add(99); on its own line compiles and does nothing, because the new array it returns is thrown away. Writing a = a.add(99); is what keeps the result.

Construction

An array is built from a literal, [e1, e2, ...] (a Range written inside spreads into its elements), or with Array() for an empty one. Array(n, fill) makes an array of n copies of fill, and the element type is inferred from the fill. A declaration with no initializer, Array<int> xs;, is the empty array.

Method-level generics

map, select, reduce, flatMap, sortBy, groupBy, join and a few others are generic on their own, apart from the element type of the array. The result type comes from what the lambda returns, so a map can change the element type, including through a chain of maps. reduce takes a seed whose type is the type of the result.

Construction, map across types, and aggregates

Array<int> filled = Array(3, 7);
console.writeln(filled);
Array<int> empty = Array();
console.writeln(empty.length());
Array<string> labels = [1, 2, 3].map((n) => n * 2).map((n) => "v${n}");
console.writeln(labels);
console.writeln(labels.joinToString("+"));
Array<int> squares = [1, 2, 3, 4].where((n) => n % 2 == 0).map((n) => n * n);
console.writeln(squares);
console.writeln([1, 2, 3, 4].reduce(0, (acc, n) => acc + n));
console.writeln(std::sum([1, 2, 3]));
console.writeln(std::average([1, 2, 4]));
Array<int> none = [];
console.writeln(std::max(none) == None);
console.writeln(std::min([4, 2, 8]));
[7, 7, 7]
0
[v2, v4, v6]
v2+v4+v6
[4, 16]
10
6
2.333333
true
2

Aggregates

sum, min, max and average are free functions in std, not methods. std::sum has an Array<int> overload that returns an int and an Array<float> overload that returns a float. std::min and std::max return an optional, None for an empty array, and std::average always returns a float.

Rules

  • No Array method mutates its receiver. Rebind the variable to keep a result.
  • at(i), a[i] and first() throw RuntimeException for an index out of range; firstOrNone() and lastOrNone() return None instead. slice(from, len), insertAt, removeAt and with also throw on a bad index, unlike string.subStr, which clamps.
  • sort(cmp) is stable: elements that compare equal keep their relative order. sortBy(key) orders by a key with <; orderBy(key) starts a multi-key sort (see std.OrderedArray).
  • unique() removes duplicates by == and keeps the first occurrence; it is named unique because distinct is a reserved keyword.
  • zip stops at the shorter of the two arrays; join and groupJoin pair elements of two arrays by a predicate and return Pair values.
  • asSeq() turns an array into a lazy sequence (see std.Seq); the methods on Array itself are eager and each runs to completion, producing a full new array.

Examples

Bounds, safe access and pure updates

Array<int> a = [10, 20, 30, 40];
console.writeln(a.slice(1, 2));
try {
    console.writeln(a.at(9));
} catch (RuntimeException e) {
    console.writeln("at: ${e.message}");
}
console.writeln(a.firstOrNone());
Array<int> none = [];
console.writeln(none.firstOrNone() == None);
console.writeln(a.with(1, 99));
console.writeln(a.insertAt(1, 15));
console.writeln(a.removeAt(0));
console.writeln(a);
[20, 30]
at: index 9 out of bounds (length 4)
10
true
[10, 99, 30, 40]
[10, 15, 20, 30, 40]
[20, 30, 40]
[10, 20, 30, 40]

Stable sort, groupBy, zip and unique

struct Person { string name; int age; }
Array<Person> people = [Person("ann", 30), Person("bob", 25), Person("cy", 30), Person("di", 25)];
Array<Person> byAge = people.sort((x, y) => x.age - y.age);
for (Person p in byAge) { console.writeln("${p.name} ${p.age}"); }
console.writeln(people.sortBy((p) => p.name).map((p) => p.name));
Map<bool, Array<int>> parity = [1, 2, 3, 4, 5].groupBy((n) => n % 2 == 0);
console.writeln(parity);
Array<Pair<int, string>> pairs = [1, 2, 3].zip(["x", "y"]);
console.writeln(pairs.length());
console.writeln(pairs[1].second);
console.writeln([1, 2, 2, 3, 1].unique());
bob 25
di 25
ann 30
cy 30
[ann, bob, cy, di]
{false: [1, 3, 5], true: [2, 4]}
2
y
[1, 2, 3]

Notes

joinToString(sep) writes the elements as text with sep between them. concatAll() is meant for an Array<string>: it joins all the parts in one pass and is what StringBuilder.toString() uses. To print an array, pass it to console.writeln directly, or turn it into text with joinToString.

Examples

Building arrays without changing the original

Array<int> a = [3, 1, 2];
Array<int> b = a.add(4).sort((x, y) => x - y);
console.writeln(a);
console.writeln(b);
console.writeln(b.map((x) => x * 10).where((x) => x > 10));
console.writeln(b.reduce(0, (sum, x) => sum + x));
[3, 1, 2]
[1, 2, 3, 4]
[20, 30, 40]
10

Constructors

new

new()

Create an empty array.

Array<int> a = Array(); and Array<int> a = []; are the same value, and so is a declaration without an initializer.

Examples

An empty array

Array<int> a = Array();
console.writeln(a.length());
console.writeln(a.isEmpty());
a = a.add(5);
console.writeln(a);
0
true
[5]
new(int n, T fill)

Create an array of n elements that are all fill.

The element type is taken from fill. Passing 0 for n gives an empty array.

Parameters

n
How many elements the array has.
fill
The value every element starts with.

Accessors

[]

get [](int i)

The element at index i, written a[i].

Assigning to an index, a[i] = v, rebinds the variable to a copy of the array in which element i is v (the same result as with(i, v)); other variables that held the old array still see the old value.

Parameters

i
A zero-based index, from 0 to length() - 1.

Throws

RuntimeException
when i is negative or not less than length().

Examples

Indexing and index assignment

Array<int> a = [10, 20, 30];
Array<int> b = a;
b[1] = 99;
console.writeln(a[1]);
console.writeln(b[1]);
20
99

Methods

add

add(T item) -> Array<T>

Return a new array with item appended at the end.

The receiver is not changed; rebind the result to keep the addition.

Parameters

item
The value to append.

Returns

A copy of this array with item as its last element.

Examples

Appending

Array<int> a = [1, 2];
Array<int> b = a.add(3);
console.writeln(a);
console.writeln(b);
a = a.add(9);
console.writeln(a);
[1, 2]
[1, 2, 3]
[1, 2, 9]

all

all((T) => bool pred) -> bool

Whether every element satisfies pred.

The scan stops at the first element for which pred is false. An empty array gives true.

Parameters

pred
The test applied to each element.

Returns

true if every element passes pred.

Examples

Universal test

Array<int> a = [2, 4, 6];
console.writeln(a.all((x) => x % 2 == 0));
console.writeln(a.add(7).all((x) => x % 2 == 0));
Array<int> e = [];
console.writeln(e.all((x) => x > 100));
true
false
true

any

any((T) => bool pred) -> bool

Whether at least one element satisfies pred.

The scan stops at the first element for which pred is true. An empty array gives false.

Parameters

pred
The test applied to each element.

Returns

true if some element passes pred.

Examples

Existence test

Array<int> a = [1, 3, 5, 6];
console.writeln(a.any((x) => x % 2 == 0));
console.writeln(a.any((x) => x > 10));
true
false

asSeq

asSeq() -> Seq<T>

View the array as a lazy Seq.

Arrays evaluate each step eagerly. A Seq pipeline does no work until a terminal operation such as toArray or firstOrNone pulls elements through it, and then handles one element at a time. Convert with asSeq when you only need part of the result, or want the steps interleaved.

Returns

A lazy sequence over the elements of the array.

Examples

Laziness shown by a trace

Array<int> a = [1, 2, 3, 4];
Seq<int> s = a.asSeq().map((x) => {
    console.writeln("map ${x}");
    return x * 10;
});
console.writeln("built");
console.writeln(s.firstOrNone());
built
map 1
10

See also: Seq

at

at(int i) -> T

The element at index i.

a.at(i) and a[i] are the same operation.

Parameters

i
A zero-based index, from 0 to length() - 1.

Returns

The element at i.

Throws

RuntimeException
when i is negative or not less than length().

Examples

Reading by index

Array<int> a = [10, 20, 30];
console.writeln(a.at(1));
console.writeln(a[2]);
try {
    console.writeln(a.at(3));
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
20
30
caught: index 3 out of bounds (length 3)

concat

concat(Array<T> other) -> Array<T>

Return a new array holding the elements of this array followed by the elements of other.

Neither input is changed.

Parameters

other
The array whose elements are appended.

Returns

The combined array.

Examples

Joining two arrays

Array<int> a = [1, 2];
Array<int> b = [3, 4];
console.writeln(a.concat(b));
console.writeln(a);
console.writeln(b);
[1, 2, 3, 4]
[1, 2]
[3, 4]

concatAll

concatAll() -> string

Concatenate every string of the array into one string, with nothing in between.

This is only meaningful on an Array<string>; it is the single-pass operation StringBuilder uses to produce its text. Call it only on an Array<string>; for any other element type the result is meaningless.

Returns

All the strings joined end to end.

Examples

Joining pieces

Array<string> parts = ["ab", "cd", "e"];
console.writeln(parts.concatAll());
Array<string> none = [];
console.writeln("[" + none.concatAll() + "]");
abcde
[]

See also: StringBuilder

contains

contains(T item) -> bool

Whether any element equals item, compared with ==.

Parameters

item
The value to look for.

Returns

true if the array holds an equal element.

Examples

Membership

Array<string> a = ["red", "green"];
console.writeln(a.contains("green"));
console.writeln(a.contains("blue"));
true
false

See also: indexOf

count

count((T) => bool pred) -> int

The number of elements that satisfy pred.

Parameters

pred
The test applied to each element.

Returns

How many elements pass pred.

Examples

Counting matches

Array<int> a = [1, 2, 3, 4, 5, 6];
console.writeln(a.count((x) => x > 3));
console.writeln(a.count((x) => x > 10));
3
0

filter

filter((T) => bool pred) -> Array<T>

Return a new array of the elements for which pred is true; another name for where.

Parameters

pred
The test applied to each element; elements for which it returns true are kept.

Returns

A new array holding the matching elements.

Examples

Keeping long words

Array<string> words = ["a", "tree", "is", "tall"];
console.writeln(words.filter((w) => w.length() > 2));
[tree, tall]

See also: where

find

find((T) => bool pred) -> T | None

The first element for which pred is true, or None when there is none.

The scan stops at the first match, so pred is not called on later elements.

Parameters

pred
The test applied to each element in order.

Returns

The first matching element, or None.

Examples

Finding the first match

Array<int> a = [3, 8, 12, 5];
console.writeln(a.find((x) => x > 5));
console.writeln(a.find((x) => x > 100));
8
None

See also: indexWhere

first

first() -> T

The first element.

Returns

The element at index 0.

Throws

RuntimeException
when the array is empty.

Examples

First element

Array<string> a = ["a", "b", "c"];
console.writeln(a.first());
Array<string> e = [];
try {
    console.writeln(e.first());
} catch (RuntimeException ex) {
    console.writeln("caught: ${ex.message}");
}
a
caught: index 0 out of bounds (length 0)

See also: firstOrNone

firstOrNone

firstOrNone() -> T | None

The first element, or None when the array is empty.

Returns

The first element, or None.

Examples

An empty array gives None instead of throwing

Array<int> a = [4, 5];
Array<int> e = [];
console.writeln(a.firstOrNone());
console.writeln(e.firstOrNone());
4
None

See also: first

flatMap

flatMap<U>((T) => Array<U> fn) -> Array<U>

Apply fn to every element and join the arrays it returns into one new array.

Parameters

fn
Called for each element; returns the array of items to contribute to the result.

Returns

The concatenation of all the arrays returned by fn, in order.

Examples

Expanding each element

Array<int> a = [1, 2, 3];
console.writeln(a.flatMap((x) => [x, x * 10]));
console.writeln(a.flatMap((x) => x == 2 ? [] : [x]));
[1, 10, 2, 20, 3, 30]
[1, 3]

forEach

forEach((T) => void fn) -> void

Call fn on every element, in order, for its side effects.

Parameters

fn
The action to perform on each element.

Examples

Printing every element

Array<string> a = ["x", "y"];
a.forEach((s) => console.writeln("item " + s));
item x
item y

groupBy

groupBy<K>((T) => K key) -> Map<K, Array<T>>

Group the elements by a key computed from each one.

The result maps each distinct key to the array of elements that produced it, in their original order. Keys appear in the map in the order they were first seen.

Parameters

key
Computes the grouping key of an element.

Returns

A Map from each key to the elements that have it.

Examples

Grouping numbers by parity

Array<int> a = [1, 2, 3, 4, 5];
Map<string, Array<int>> g = a.groupBy((x) => x % 2 == 0 ? "even" : "odd");
console.writeln(g.at("odd"));
console.writeln(g.at("even"));
console.writeln(g.keys());
[1, 3, 5]
[2, 4]
[odd, even]

groupJoin

groupJoin<U>(Array<U> other, (T, U) => bool pred) -> Array<Pair<T, Array<U>>>

Pair each element of this array with the array of all elements of other that match it.

Unlike join, every element of this array appears exactly once in the result, with an empty array when nothing in other matched.

Parameters

other
The array to match against.
pred
The match condition, called with an element of this array and an element of other.

Returns

A new array with one Pair per element of this array: the element and its matches.

Examples

Grouping words under their first letter

Array<string> letters = ["a", "b", "z"];
Array<string> words = ["apple", "avocado", "banana"];
Array<Pair<string, Array<string>>> g =
    letters.groupJoin(words, (l, w) => w.startsWith(l));
for (Pair<string, Array<string>> p in g) {
    console.writeln("${p.first}: ${p.second.length()}");
}
a: 2
b: 1
z: 0

See also: join

indexOf

indexOf(T item) -> int

The index of the first element equal to item, compared with ==.

Parameters

item
The value to look for.

Returns

The zero-based index of the first match, or -1 when no element matches.

Examples

Locating an element

Array<string> a = ["red", "green", "red"];
console.writeln(a.indexOf("red"));
console.writeln(a.indexOf("green"));
console.writeln(a.indexOf("blue"));
0
1
-1

See also: contains, indexWhere

indexWhere

indexWhere((T) => bool pred) -> int

The index of the first element for which pred is true.

Parameters

pred
The test applied to each element in order.

Returns

The zero-based index of the first match, or -1 when no element passes.

Examples

Locating by condition

Array<int> a = [4, 7, 10];
console.writeln(a.indexWhere((x) => x > 5));
console.writeln(a.indexWhere((x) => x > 50));
1
-1

See also: find, indexOf

insertAt

insertAt(int i, T v) -> Array<T>

Return a new array with v inserted so that it ends up at index i.

The element previously at i and everything after it move one place later. i may equal length(), which appends. The receiver is not changed.

Parameters

i
The index the new element will have, from 0 to length().
v
The value to insert.

Returns

A new array one element longer than the receiver.

Throws

RuntimeException
when i is negative or greater than length().

Examples

Inserting in the middle

Array<int> a = [1, 2, 4];
console.writeln(a.insertAt(2, 3));
console.writeln(a.insertAt(3, 5));
console.writeln(a);
try {
    a.insertAt(9, 0);
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
[1, 2, 3, 4]
[1, 2, 4, 5]
[1, 2, 4]
caught: insertAt: index out of bounds

See also: removeAt

isEmpty

isEmpty() -> bool

Whether the array has no elements.

Returns

true when length() is 0.

Examples

Testing for empty

Array<int> a = [];
console.writeln(a.isEmpty());
console.writeln(a.add(1).isEmpty());
true
false

iterator

iterator() -> IIterator<T>

Return an iterator over the elements, front to back.

This is what lets an array be passed where an IIterable<T> is expected, for example to a function that accepts any iterable. A for loop over an array does not need it. The iterator walks a snapshot, so later rebinding of the variable never affects an iterator already created.

Returns

An iterator positioned before the first element.

Examples

Walking an array by hand

Array<string> a = ["x", "y", "z"];
IIterator<string> it = a.iterator();
while (it.hasNext()) {
    console.writeln(it.next());
}
x
y
z

join

join<U>(Array<U> other, (T, U) => bool pred) -> Array<Pair<T, U>>

Pair up elements of this array with elements of other for which pred is true.

Every element of this array is tested against every element of other, in order, and each pair that passes is added to the result as a Pair of the two. An element can appear in several pairs, or in none. This is a nested loop, so the work grows with the product of the two lengths. It is not the same as joinToString, which builds text.

Parameters

other
The array to match against.
pred
The match condition, called with an element of this array and an element of other.

Returns

A new array of Pair<T, U> values, ordered by this array first, then by other.

Examples

Matching orders to customers

Array<int> customers = [1, 2, 3];
Array<int> orders = [10, 21, 22, 11];
Array<Pair<int, int>> pairs = customers.join(orders, (c, o) => o / 10 == c);
for (Pair<int, int> p in pairs) {
    console.writeln("customer ${p.first} order ${p.second}");
}
customer 1 order 10
customer 1 order 11
customer 2 order 21
customer 2 order 22

See also: groupJoin

joinToString

joinToString(string sep) -> string

Join the elements into one string, with sep between neighbours.

Each element is converted with its toString(). An empty array gives "", and a one-element array gives just that element's text with no separator.

Parameters

sep
The text placed between consecutive elements.

Returns

The joined text.

Examples

Comma-separated list

Array<int> a = [1, 2, 3];
console.writeln(a.joinToString(", "));
console.writeln(a.joinToString(""));
Array<int> e = [];
console.writeln("[" + e.joinToString(", ") + "]");
1, 2, 3
123
[]

last

last() -> T

The last element.

Returns

The element at index length() - 1.

Throws

RuntimeException
when the array is empty.

Examples

Last element

Array<string> a = ["a", "b", "c"];
console.writeln(a.last());
Array<string> e = [];
try {
    console.writeln(e.last());
} catch (RuntimeException ex) {
    console.writeln("caught: ${ex.message}");
}
c
caught: index -1 out of bounds (length 0)

See also: lastOrNone

lastOrNone

lastOrNone() -> T | None

The last element, or None when the array is empty.

Returns

The last element, or None.

Examples

An empty array gives None instead of throwing

Array<int> a = [4, 5];
Array<int> e = [];
console.writeln(a.lastOrNone());
console.writeln(e.lastOrNone());
5
None

See also: last

length

length() -> int

The number of elements in the array.

Returns

The element count; 0 for an empty array.

Examples

Counting elements

Array<string> names = ["ada", "grace", "edsger"];
console.writeln(names.length());
console.writeln(names.add("alan").length());
console.writeln(names.length());
3
4
3

map

map<U>((T) => U fn) -> Array<U>

Return a new array made by applying fn to every element.

The result has the same length as the receiver and may have a different element type. The receiver is not changed. select is another name for the same operation.

Parameters

fn
The transformation applied to each element, in order.

Returns

A new array of the results of fn.

Examples

Squaring numbers and converting them to text

Array<int> a = [1, 2, 3];
Array<int> squares = a.map((x) => x * x);
Array<string> labels = a.map((x) => "n" + x.toString());
console.writeln(squares);
console.writeln(labels);
console.writeln(a);
[1, 4, 9]
[n1, n2, n3]
[1, 2, 3]

See also: select

maxBy

maxBy<K>((T) => K key) -> T | None

The element with the largest key, or None for an empty array.

If several elements share the largest key, the first of them is returned.

Parameters

key
Computes the key compared with <.

Returns

The element whose key is largest, or None.

Examples

Longest word

Array<string> w = ["pear", "fig", "plum", "ox", "kiwi"];
console.writeln(w.maxBy((s) => s.length()));
Array<string> e = [];
console.writeln(e.maxBy((s) => s.length()));
pear
None

See also: minBy

minBy

minBy<K>((T) => K key) -> T | None

The element with the smallest key, or None for an empty array.

If several elements share the smallest key, the first of them is returned.

Parameters

key
Computes the key compared with <.

Returns

The element whose key is smallest, or None.

Examples

Shortest word

Array<string> w = ["pear", "fig", "plum", "elk"];
console.writeln(w.minBy((s) => s.length()));
Array<string> e = [];
console.writeln(e.minBy((s) => s.length()));
fig
None

See also: maxBy

orderBy

orderBy<K>((T) => K key) -> OrderedArray<T>

Start a multi-key sort: order by key, and let thenBy break ties.

The result is an OrderedArray that is already sorted by key (stably) and can be refined with further thenBy calls or turned back into an array with toArray. The receiver is not changed.

Parameters

key
Computes the primary sort key of an element.

Returns

An OrderedArray sorted by key.

Examples

Sorting by one key

Array<string> w = ["pear", "fig", "plum", "kiwi"];
console.writeln(w.orderBy((s) => s.length()).toArray());
[fig, pear, plum, kiwi]

See also: thenBy

reduce

reduce<A>(A seed, (A, T) => A fn) -> A

Fold the elements into a single value, from the first element to the last.

Starting with seed, the result of each step is passed to the next call as the first argument of fn, with the next element as the second. An empty array returns seed unchanged.

Parameters

seed
The starting value of the accumulator.
fn
Combines the accumulator so far with the next element and returns the new accumulator.

Returns

The final accumulator.

Examples

Sum and string building

Array<int> a = [1, 2, 3, 4];
console.writeln(a.reduce(0, (sum, x) => sum + x));
console.writeln(a.reduce("", (s, x) => s + x.toString()));
Array<int> e = [];
console.writeln(e.reduce(7, (sum, x) => sum + x));
10
1234
7

removeAt

removeAt(int i) -> Array<T>

Return a new array without the element at index i.

The elements after i move one place earlier. The receiver is not changed.

Parameters

i
The index of the element to remove, from 0 to length() - 1.

Returns

A new array one element shorter than the receiver.

Throws

RuntimeException
when i is negative or not less than length().

Examples

Removing an element

Array<int> a = [10, 20, 30];
console.writeln(a.removeAt(1));
console.writeln(a);
try {
    a.removeAt(3);
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
[10, 30]
[10, 20, 30]
caught: removeAt: index out of bounds

See also: insertAt

reverse

reverse() -> Array<T>

Return a new array with the elements in the opposite order.

The receiver is not changed.

Returns

A reversed copy.

Examples

Reversing

Array<int> a = [1, 2, 3];
console.writeln(a.reverse());
console.writeln(a);
[3, 2, 1]
[1, 2, 3]

select

select<U>((T) => U fn) -> Array<U>

Return a new array made by applying fn to every element; another name for map.

Parameters

fn
The transformation applied to each element, in order.

Returns

A new array of the results of fn.

Examples

Selecting a field

Array<string> names = ["ada", "grace"];
console.writeln(names.select((n) => n.length()));
[3, 5]

See also: map

skip

skip(int k) -> Array<T>

Return a new array without the first k elements.

If the array has k or fewer elements the result is empty. The receiver is not changed.

Parameters

k
How many elements to drop from the front; it must not be negative.

Returns

A new array holding the remaining elements.

Throws

RuntimeException
when k is negative.

Examples

Dropping a prefix

Array<int> a = [1, 2, 3, 4, 5];
console.writeln(a.skip(2));
console.writeln(a.skip(99));
console.writeln(a.skip(0));
[3, 4, 5]
[]
[1, 2, 3, 4, 5]

See also: take

skipWhile

skipWhile((T) => bool pred) -> Array<T>

Return a new array without the leading elements for which pred is true.

Once an element fails pred, it and everything after it are kept, even later elements that would pass.

Parameters

pred
The test applied to each element from the front.

Returns

The array starting at the first element that fails pred.

Examples

Skipping while small

Array<int> a = [1, 2, 9, 3];
console.writeln(a.skipWhile((x) => x < 5));
[9, 3]

See also: takeWhile

slice

slice(int start, int len) -> Array<T>

Return a new array of len elements beginning at index start.

Unlike string.subStr, a range that does not fit is an error rather than being clamped. The receiver is not changed.

Parameters

start
The index of the first element to copy.
len
How many elements to copy; may be 0.

Returns

A new array of exactly len elements.

Throws

RuntimeException
when start or len is negative, or start + len is greater than length().

Examples

Taking a window

Array<int> a = [10, 20, 30, 40, 50];
console.writeln(a.slice(1, 3));
console.writeln(a.slice(5, 0));
try {
    a.slice(3, 4);
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
[20, 30, 40]
[]
caught: slice: out of bounds

sort

sort((T, T) => int cmp) -> Array<T>

Return a new array with the elements ordered by the comparison function cmp.

cmp(a, b) must return a negative number when a belongs before b, a positive number when a belongs after b, and 0 when they are equivalent. The sort is stable: elements that compare equal keep their original relative order. The receiver is not changed.

Parameters

cmp
The comparison function.

Returns

A new, sorted array.

Examples

Sorting numbers and then keeping ties in order

Array<int> a = [3, 1, 2];
console.writeln(a.sort((x, y) => x - y));
console.writeln(a.sort((x, y) => y - x));
Array<string> w = ["pear", "fig", "plum", "kiwi"];
console.writeln(w.sort((x, y) => x.length() - y.length()));
console.writeln(a);
[1, 2, 3]
[3, 2, 1]
[fig, pear, plum, kiwi]
[3, 1, 2]

See also: sortBy, orderBy

sortBy

sortBy<K>((T) => K key) -> Array<T>

Return a new array ordered by a key computed from each element, smallest key first.

The key type K must support the < operator, as int, float and string do. The sort is stable: elements with equal keys keep their original relative order. The receiver is not changed. For several keys, use orderBy followed by thenBy.

Parameters

key
Computes the sort key of an element.

Returns

A new array in ascending key order.

Examples

Sorting words by length

Array<string> w = ["pear", "fig", "plum", "kiwi"];
console.writeln(w.sortBy((s) => s.length()));
console.writeln(w.sortBy((s) => s));
[fig, pear, plum, kiwi]
[fig, kiwi, pear, plum]

See also: sort, orderBy

take

take(int k) -> Array<T>

Return a new array of the first k elements.

If the array has fewer than k elements the result is a copy of the whole array. A k of zero or less gives an empty array. The receiver is not changed.

Parameters

k
How many elements to keep from the front.

Returns

A new array of at most k elements.

Examples

Taking a prefix

Array<int> a = [1, 2, 3, 4, 5];
console.writeln(a.take(2));
console.writeln(a.take(99));
console.writeln(a.take(0));
[1, 2]
[1, 2, 3, 4, 5]
[]

See also: skip

takeWhile

takeWhile((T) => bool pred) -> Array<T>

Return a new array of the leading elements for which pred is true.

The result stops at the first element that fails pred; later elements are dropped even if they would pass.

Parameters

pred
The test applied to each element from the front.

Returns

The longest prefix whose elements all pass pred.

Examples

Taking while small

Array<int> a = [1, 2, 9, 3];
console.writeln(a.takeWhile((x) => x < 5));
[1, 2]

See also: skipWhile

unique

unique() -> Array<T>

Return a new array with duplicate elements removed.

Elements are compared with ==, and the first occurrence of each value is the one kept, so the order of the survivors is their original order. The receiver is not changed.

Returns

A copy of the array in which no value appears twice.

Examples

Removing duplicates

Array<int> a = [3, 1, 3, 2, 1];
console.writeln(a.unique());
console.writeln(a);
[3, 1, 2]
[3, 1, 3, 2, 1]

where

where((T) => bool pred) -> Array<T>

Return a new array of the elements for which pred is true, in their original order.

The receiver is not changed. filter is another name for the same operation.

Parameters

pred
The test applied to each element; elements for which it returns true are kept.

Returns

A new array holding the matching elements.

Examples

Keeping the even numbers

Array<int> a = [1, 2, 3, 4, 5, 6];
console.writeln(a.where((x) => x % 2 == 0));
console.writeln(a);
[2, 4, 6]
[1, 2, 3, 4, 5, 6]

See also: filter

with

with(int i, T v) -> Array<T>

Return a new array in which the element at index i is replaced by v.

This is the explicit form of the index assignment a[i] = v. The receiver is not changed.

Parameters

i
The index to replace, from 0 to length() - 1.
v
The new value for that position.

Returns

A copy of the array with one element changed.

Throws

RuntimeException
when i is negative or not less than length().

Examples

Replacing one element

Array<string> a = ["x", "y", "z"];
console.writeln(a.with(1, "Y"));
console.writeln(a);
[x, Y, z]
[x, y, z]

withIndex

withIndex() -> Array<Pair<int, T>>

Return a new array pairing every element with its index.

Returns

An array of Pair<int, T> values: first is the index, second is the element.

Examples

Numbering elements

Array<string> a = ["a", "b", "c"];
for (Pair<int, string> p in a.withIndex()) {
    console.writeln("${p.first}: ${p.second}");
}
0: a
1: b
2: c

zip

zip<U>(Array<U> other) -> Array<Pair<T, U>>

Pair up the elements of two arrays by position.

The result has the length of the shorter array; extra elements of the longer one are ignored.

Parameters

other
The array that supplies the second element of each pair.

Returns

A new array of Pair<T, U> values: element i of this array with element i of other.

Examples

Zipping names with scores

Array<string> names = ["ada", "bob", "cy"];
Array<int> scores = [90, 80];
for (Pair<string, int> p in names.zip(scores)) {
    console.writeln("${p.first}=${p.second}");
}
ada=90
bob=80

See also

  • Collections are values — Array, Map and Set never change in place; every changing method returns a new collection, and the idiom for change is to rebind.
  • OrderedArray — An array that has been sorted by one or more keys, produced by Array.orderBy and thenBy.
  • Seq — A lazy sequence: a pipeline of steps that does no work until its result is requested.
  • Map — An associative collection from keys of type K to values of type V, with value semantics.
  • Pair — A pair of two values, possibly of different types.