Collections
A collection groups several elements into one value. This page lists every operation on collections. This introduction gives the concepts you need before you read the entries: the kinds of collection, indexed and non-indexed collections, finite and infinite collections, lazy and eager collections, and element types.
Kinds of collection
| Kind | Epsil literal | Description |
|---|---|---|
| list | [1, 2, 3] | Elements in order, read by index. Duplicates are allowed. |
| set | set(1, 2, 3) | Unique elements, not in order. |
| tuple | (1, "a") | A fixed number of elements, each with its own type. |
| dictionary | {"a" -> 1, "b" -> 2} | Key-value pairs. The keys are strings. |
| range | 1..10 | Numbers from a start to an end, with an optional step. |
| string | "hello" | The characters of the text, in order. |
A set removes duplicates and stores its elements in the canonical
order, so two sets with the same elements are written, printed and walked
alike. The empty set is set(), and the empty dictionary is {}:
set(3, 1, 3, 2)
// ➔ Set(1, 2, 3)
Collections are immutable. An operation never changes a collection: it returns a new one.
let xs = [1, 2, 3]
let ys = append(xs, 4)
xs
// ➔ [1, 2, 3]
A string is a collection of its characters, so length, reverse, sort,
filter and most other operations apply to it. An operation that selects or
reorders the characters of a string (reverse, take, sort, unique,
filter) returns a string. An operation that transforms the elements (map,
flatMap, scan, zip) returns a list.
reverse("stressed")
// ➔ "desserts"
filter("banana", c => c != "a")
// ➔ "bnn"
Indexed and non-indexed collections
An indexed collection has its elements in a fixed order, and you can read an element by its position. Lists, tuples, ranges and strings are indexed.
A non-indexed collection has no positions. You can enumerate its elements and test membership, but you cannot read an element by index. Sets and dictionaries are non-indexed. You read a dictionary value by its key.
The first element has index 1. A negative index counts from the end of a
finite collection: -1 is the last element, -2 the element before it.
[2, 5, 7, 11][3]
// ➔ 7
[2, 5, 7, 11][-3]
// ➔ 5
{a -> 1, b -> 2}["b"]
// ➔ 2
An index that is out of range does not stop the program. It gives an absence
marker: NaN when the elements are numbers, Missing otherwise. See
at for the details.
Membership works on every collection:
3 in set(1, 2, 3)
// ➔ true
Nested collections
The elements of a collection are its top-level elements. A matrix (a list
of lists) is a collection of rows. So count of a matrix is its number of
rows, and first is its first row:
count([[2, 3, 4], [6, 7, 9]])
// ➔ 2
first([[2, 3, 4], [6, 7, 9]])
// ➔ [2, 3, 4]
To read one entry of a nested collection, give one index per level:
[[2, 3, 4], [6, 7, 9]][2, 3]
// ➔ 9
The Linear Algebra page has the operations on vectors, matrices and tensors.
Finite and infinite collections
A collection can be finite (it has a definite number of elements) or
infinite. 1..oo is the positive integers, and the number sets such as
integers, realNumbers and primes are infinite sets.
count(1..oo)
// ➔ +oo
Lazy and eager collections
An eager collection has all its elements computed when it is made. The list, set, tuple and dictionary literals are eager.
A lazy collection computes an element only when something reads it. A
range, map, filter, take, a comprehension, cycle, iterate and
repeat make lazy collections. Because of this, you can work with an
infinite collection when you read only a finite part of it:
1..oo |> filter(isPrime) |> take(10) |> listFrom
// ➔ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Only the first ten primes are computed here. The elements of a lazy collection are computed on the first read and kept, so a second read of the same collection does not compute them again. The kept elements are computed again when a value they depend on changes.
To materialize a lazy collection, that is to compute all its elements and make an eager collection, use listFrom or setFrom:
listFrom(1..10)
// ➔ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
When a lazy collection is printed, only its first elements are computed. An ellipsis shows that more elements follow:
map(x => x^2, 1..oo)
// ➔ [1, 4, 9, 16, 25, …]
Use a range, not a number set, as an infinite indexed source
integers and the other number sets are sets. They have no order and no
indexes. The operations that need an indexed collection (at, take,
drop, first, second, third, last, rest, most) reject them with
an incompatible-type error. filter keeps the kind of its source, so
filter(integers, x => x > 0) is a set too.
For an infinite source that you can index and take from, use 1..oo. To test
membership in a number set, use in:
filter(1..30, x => x in primes)
// ➔ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
The materialization cap
The engine setting maxCollectionSize (default 10000) limits how many
elements a lazy collection can have when the engine changes it into a list
by itself, for example to print or evaluate a result. Such an automatic
conversion keeps the lazy form when the list would be larger. You can still
read the elements one at a time, and operations such as length still work.
An explicit conversion with listFrom or setFrom does not check the
setting: listFrom(1..20000) makes the whole list.
repeat(7, 3)
// ➔ [7, 7, 7]
repeat(7, 20000)
// ➔ Repeat(7, 20000)
length(repeat(7, 20000))
// ➔ 20000
The cap applies only to materialization. An operation applied to each element
of a lazy collection (such as + over a range) is not limited by it.
Element types
The type of a collection includes the type of its elements: list<integer>,
set<string>, tuple<integer, string>, dictionary<number>. A dictionary
with a fixed set of known keys has a record type, such as
record{x: integer}. A list of numbers with a known length has a vector type,
such as vector<integer^3>.
(type([1, 2, 3]), type(set(1, 2)), type((1, "a")), type({x -> 1}))
// ➔ (TypeFrom("vector<integer^3>"), TypeFrom("set<integer>"), TypeFrom("tuple<integer, string>"), TypeFrom("record{x: integer}"))
When the elements have different types, the element type is their union:
type(["a", 1])
// ➔ TypeFrom("list<integer | string>")
In a signature, collection means any collection, indexed or not, finite or
infinite. indexed_collection means a collection that you can read by index,
such as a list, a tuple, a range or a string.
Functions as arguments
Many operations take a function: a predicate for filter, any or
countIf, a key for sort or groupBy, a reducer for reduce. You can
write it as an anonymous function, x => x > 5, or as an expression with the
placeholder _, _ > 5:
countIf([5, 2, 10, 18], _ > 5)
// ➔ 2
Where the function goes
An operation that takes one collection and a function takes the collection
first and the function second: filter(xs, p), flatMap(xs, f),
sort(xs, key), reduce(xs, f, initial).
map is the exception: the function is its first argument, map(f, xs).
map takes any number of collections and calls the function with one element
of each, so the function has the one fixed position and the collections
follow it:
map((x, y) => x + y, [1, 2, 3], [10, 20, 30])
// ➔ [11, 22, 33]
fold(f, initial, xs) also takes its function first. It is reduce with the
arguments in another order.
An argument in the wrong position is an incompatible-type error:
map([1, 2, 3], x => x^2) reports that the list is not a function. When the
two arguments are in each other's place, the diagnostic says that they look
exchanged, and its fixit exchanges them.
The pipe |> passes a collection to the next operation, so a sequence of
operations reads from left to right. The collection fills the argument slot
the operation is missing, so the pipe is the same for both orders:
xs |> filter(isPrime) is filter(xs, isPrime), and xs |> map(f) is
map(f, xs). A
comprehension is another way to make a
filtered and transformed list:
1..10 |> filter(isPrime) |> map(x => x^2)
// ➔ [4, 9, 25, 49]
[x^2 for x in 1..10 if x % 2 == 1]
// ➔ [1, 9, 25, 49, 81]
See Pipe for the complete rules of the pipe.
Definitions
Each definition is listed under its Epsil spelling (the MathJSON name when it has none), with its signature in the engine's type syntax. The Standard Library page is the one-page index of every category.
adjoin
MathJSON Adjoin · (set<any>, any+) -> set
- argument 1 — The base ring. Sample:
integers. - arguments 2, … — An element adjoined to the ring: an algebraic number, or a symbol for an indeterminate. Sample:
sqrt(2).
The ring obtained by adjoining one or more elements to a base ring.
adjoin(integers, sqrt(2)) is ℤ[√2]; adjoin(integers, ["Complex", 0, 1]) is the Gaussian integers ℤ[i]; adjoin(integers, "x") is the polynomial ring ℤ[x].
Inert: the adjunction is not expanded, and membership in it is not decided.
adjoin(integers, sqrt(2))
// ➔ Adjoin(integers, sqrt(2))
all
(xs: collection<T>, predicate: ((T) any -> boolean)?) -> boolean where T
xs— The collection to test; for an empty collection the result is True. Sample:[2, 4, 6].predicate— The test of each element; without it, each element must be True. Sample:x => x > 1.
Return True if the predicate holds for every element of the collection (or if every element is True when no predicate is given).
all([2, 4, 6], x => x % 2 == 0)
// ➔ true
Without a predicate, the elements are read as booleans. all stops at the
first element that fails the predicate, so it can answer False for an
infinite collection.
all([1, 2, 3], x => x > 2)
// ➔ false
all(1..oo, x => x < 5)
// ➔ false
all of an empty collection is True. When the answer depends on elements
that cannot be decided, all stays unevaluated.
all([])
// ➔ true
all([a, b], x => x > 0)
// ➔ All([a,b], (x) => 0 < x)
MathJSON: All
["All", xs], ["All", xs, predicate].
["All", ["List", 1, 2, 3], ["Function", ["Greater", "x", 0], "x"]]
// ➔ "True"
["All", ["Range", 1, "PositiveInfinity"], ["Function", ["Less", "x", 5], "x"]]
// ➔ "False"
any
(xs: collection<T>, predicate: ((T) any -> boolean)?) -> boolean where T
xs— The collection to test; for an empty collection the result is False. Sample:[1, 3, 4].predicate— The test of each element; without it, an element must be True. Sample:x => x > 1.
Return True if the predicate holds for at least one element of the collection (or if any element is True when no predicate is given).
To test membership of a specific value, use contains(xs, v) — the structural-identity specialization any(xs, (e) => e === v).
any([1, 3, 4], x => x % 2 == 0)
// ➔ true
Without a predicate, the elements are read as booleans. any stops at the
first element that satisfies the predicate, so it can answer True for an
infinite collection.
any([False, True, False])
// ➔ true
any(1..oo, x => x > 5)
// ➔ true
any of an empty collection is False. When the answer depends on
elements that cannot be decided, any stays unevaluated.
any([])
// ➔ false
any([a, b], x => x > 0)
// ➔ Any([a,b], (x) => 0 < x)
To test whether a collection holds one value, use
contains, which compares by structural identity, not with the
tolerant ==.
MathJSON: Any
["Any", xs], ["Any", xs, predicate].
["Any", ["List", 1, 2, 3], ["Function", ["Greater", "x", 2], "x"]]
// ➔ "True"
["Any", ["Range", 1, "PositiveInfinity"], ["Function", ["Greater", "x", 5], "x"]]
// ➔ "True"
append
(collection<any>, any+) -> collection
- argument 1 — The collection to extend. Sample:
[1, 2]. - arguments 2, … — An element to add, after the elements before it. Sample:
3.
Return the collection with one or more elements added at its end.
append([1, 2], 3, 4)
// ➔ [1,2,3,4]
Collections are immutable: append returns a new collection and does not
change its argument.
MathJSON: Append
["Append", xs, element, …].
["Append", ["List", 1, 2], 3]
// ➔ ["List", 1, 2, 3]
argMax
(xs: indexed_collection<T>, key: ((T) any -> unknown)?) -> integer where T
xs— The collection to search; an empty collection leaves the call unevaluated. Sample:[3, 9, 2].key— The function whose values are compared; without it, the elements themselves are compared. Sample:x => x^2.
Return the 1-based index of the element that maximizes the given key function (or of the largest element when no key is given); of several such elements, the first.
argMax([3, 9, 2])
// ➔ 2
With a key function, the keys are compared; without one, the elements. On a
tie, the first index wins. argMax stays unevaluated on an empty or
infinite collection, or when a comparison cannot be decided.
[argMax([5, 2, 10, 18]), argMax([-3, 1, -2], abs)]
// ➔ [4,1]
argMax(1..oo)
// ➔ ArgMax(1..oo)
MathJSON: ArgMax
["ArgMax", xs], ["ArgMax", xs, key].
["ArgMax", ["List", -3, 1, -2], ["Function", ["Abs", "x"], "x"]]
// ➔ 1
argMin
(xs: indexed_collection<T>, key: ((T) any -> unknown)?) -> integer where T
xs— The collection to search; an empty collection leaves the call unevaluated. Sample:[3, 9, 2].key— The function whose values are compared; without it, the elements themselves are compared. Sample:x => x^2.
Return the 1-based index of the element that minimizes the given key function (or of the smallest element when no key is given); of several such elements, the first.
argMin([3, 9, 2])
// ➔ 3
With a key function, the keys are compared; without one, the elements. On a
tie, the first index wins. argMin stays unevaluated on an empty or
infinite collection, or when a comparison cannot be decided.
[argMin([5, 2, 10, 18]), argMin([-3, 1, -2], abs)]
// ➔ [2,2]
MathJSON: ArgMin
["ArgMin", xs], ["ArgMin", xs, key].
["ArgMin", ["List", -3, 1, -2], ["Function", ["Abs", "x"], "x"]]
// ➔ 2
arrayFrom
MathJSON ArrayFrom · (value, string?) state -> array
- argument 1 — A finite collection whose elements are the cells, or an array whose cells are copied. Sample:
[1, 2, 3]. - argument 2 — The type of the cells, as a string. Sample:
"integer<0..255>".
Make a new mutable array from the elements of a finite collection, or from the cells of an array, in order.
The second operand is a string that names the type of the cells, such as "integer<0..255>". Without it, the cell type is the element type that a variable initialized with the collection takes (number for a list of numbers, any for an empty list), or the cell type of an array.
Each evaluation makes a new array. A source whose length is not finite or not known leaves the expression unevaluated.
arrayFrom([1, 2, 3])
arrayFrom(repeat(0, 4), "integer<0..255>")
At
(value: any, index: (boolean | character | indexed_collection<any> | number | string)+) -> unknown
Access an element of an indexed collection.
If the index is negative, it is counted from the end.
Multiple indices can be provided to access nested collections (e.g., matrices).
If the index is a finite collection of booleans, returns the elements where the mask is True (a mask is a filter over the positions up to the shorter of the mask and the collection; a missing or NaN member keeps nothing).
If the index is a finite collection of integers, returns the elements at those indices, preserving position: an out-of-range index yields the absence marker, it is not dropped.
Out-of-band access (an out-of-range index, or a dictionary key that is not present) yields a POSITION-PRESERVING marker: NaN when the collection’s elements are numeric, missing otherwise. It never yields nothing, which would erase the position.
An index that is provably not an integer (2.5, 3/2, 5 + √17), as a scalar or as an entry of an index list, selects no element and yields the same marker. An index that cannot be decided (an unknown, an exact constant within rounding of an integer) leaves At unevaluated.
[10, 20, 30][2]
// ➔ 20
[10, 20, 30][-1]
// ➔ 30
xs[i] is At(xs, i). Indexes start at 1, and a negative index counts from
the end, -1 being the last element.
Several indexes
With several indexes, they are applied in order, one level of nesting each:
m[2, 1] and m[2][1] select the same element of a matrix. Indexing a matrix
once gives a row, which can be indexed again.
[[1, 2], [3, 4]][2, 1]
// ➔ 3
[[1, 2], [3, 4]][2][1]
// ➔ 3
A list of indexes or a mask
When the index is a list of integers, the result is the list of the elements at those positions. An out-of-range position gives the absence marker in its place.
[10, 20, 30, 40, 50][[1, 3, 5]]
// ➔ [10,30,50]
[10, 20, 30, 40, 50][[1, 3, 9]]
// ➔ [10,30,NaN]
When the index is a list of booleans, it is a mask: the result is the
elements where the mask is True, in order. The mask is read up to the
shorter of its length and the length of the collection: a shorter mask keeps
nothing past its end, and a longer one is read only as far as the collection
goes. A Missing or NaN member keeps nothing, as False does.
[10, 20, 30, 40][[True, False, True, False]]
// ➔ [10,30]
[10, 20, 30, 40][[True, False, True]]
// ➔ [10,30]
[10, 20, 30][[False, True, False, True, True]]
// ➔ [20]
[10, 20, 30, 40][[True, Missing, True, NaN]]
// ➔ [10,30]
An index with a member that is neither a boolean nor Missing or NaN is a
list of indexes. So is an index of Missing and NaN members only: it gives
an absence marker for each member.
[10, 20, 30][[1, Missing]]
// ➔ [10,NaN]
[10, 20, 30][[Missing, NaN]]
// ➔ [NaN,NaN]
Out-of-range index
An index outside the collection, including 0, is not an error. The result
is an absence marker drawn from the element type: NaN for a numeric
collection, a point whose coordinates are all NaN for a collection of
points, and Missing otherwise. first and last of an empty collection
are out of range too.
[5, 2, 10, 18][99]
// ➔ NaN
["a", "b"][99]
// ➔ missing
[(1, 2), (3, 4)][5]
// ➔ (NaN, NaN)
first([])
// ➔ missing
The marker is not part of the static type of an access: the engine cannot in general know that an index is in range, and the type describes the values that are present. When the index is a literal that is provably out of range, the type is the type of the marker.
function f(n) { type([5, 2, 10, 18][n]) }
f(1)
// ➔ TypeFrom("integer")
type([5, 2, 10, 18][99])
// ➔ TypeFrom("nan")
type(["a", "b"][99])
// ➔ TypeFrom("missing")
Test for an absent value with isMissing, or
replace it with Coalesce, before computing on
it. These, and AssertPresent, read a
point whose coordinates are all NaN as absent, as they read NaN and
Missing. The x coordinate of an absent point is NaN. See
Absent values.
Coalesce(["a", "b"][99], "none")
// ➔ "none"
let ps = [(1, 2)]; [isMissing(ps[5]), Coalesce(ps[9], (0, 0))]
// ➔ [true,(0, 0)]
let ps = [(1, 2)]; AssertPresent(ps[5])
// ➔ error: Runtime error: expected present at `At("ps", 5)`
let ps = [(1, 2)]; pointX(ps[5])
// ➔ NaN
Filtering with a condition
A comparison of a list with a scalar (<, <=, >, >=, ==, !=) is
applied to each element and gives a list of booleans. As an index, that list
is a mask, so L[L > 0] keeps the positive elements.
let L = [-1, 2, -3, 4]; L > 0
// ➔ [false,true,false,true]
let L = [-1, 2, -3, 4]; L[L > 0]
// ➔ [2,4]
The condition need not be about the filtered list. It can test another list,
which is read as a mask up to the shorter of the two lengths, or the
positions, computed from a range; here, all the elements but the k-th:
let L = [1, 2, 3, 4, 5]; let K = [1, 0, 1]; L[K == 1]
// ➔ [1,3]
let L = [1, 2, 3, 4, 5]; let k = 2; L[abs((1..length(L)) - k) > 0]
// ➔ [1,3,4,5]
A comparison of two collections is not elementwise: it compares the whole values.
[1, 2, 3] == [1, 2, 3]
// ➔ true
Indexing a matrix or a tensor
A matrix has one index per axis: the first selects the row and the second
the column, and a tensor of rank 3 takes three indexes. A negative index
counts from the end of its own axis, so A[2, -1] is the last element of
the second row, and A[-1] is the last row.
let A = [[5, 2, 10, 18], [1, 2, 3, 4]]
[A[2, -1], A[-1]]
// ➔ [4,[1,2,3,4]]
[[[1, 2], [3, 4]], [[5, 6], [7, 8]]][2, 1, 2]
// ➔ 6
To read a column, index the transpose:
transpose([[1, 2], [3, 4]])[2]
// ➔ [2,4]
MathJSON: At • LaTeX: [
["At", xs, index], ["At", xs, ...indexes], ["At", xs, indexes] (a
collection of integers), ["At", xs, mask] (a collection of booleans).
["At", ["List", 5, 2, 10, 18], -2]
// ➔ 10
["At", ["List", ["List", 1, 2], ["List", 3, 4]], 2, 1]
// ➔ 3
["At", ["List", 10, 20, 30, 40], ["List", "True", "False", "True", "False"]]
// ➔ ["List", 10, 30]
In LaTeX, the bracket notation v[n] is always ["At", "v", "n"], and
L[L>0] filters L. When a symbol is declared with a collection type, a
subscript is an At too: with v declared list<number>, v_n is
["At", "v", "n"], v_{n+1} is ["At", "v", ["Add", "n", 1]] and v_{p,q}
is ["At", "v", "p", "q"]. The type of the At expression is the element
type of the collection, so v_n has type number and can be used in
arithmetic. In LaTeX, a bare i is the imaginary unit: use another index
symbol, such as k.
["At", ["List", ["List", 5, 2, 10, 18], ["List", 1, 2, 3, 4]], 2, -1]
// ➔ 4
In LaTeX, \mathbf{A}\lbrack 2, 3\rbrack is ["At", "A_bold", 2, 3].
chunk
((xs: S, count: integer) -> list<string> where S: string) & ((xs: indexed_collection, count: integer) -> list<list>)
xs— The list or string to split. Sample:[1, 2, 3, 4, 5, 6].count— The number of groups, at least 1; each group has ⌈length / count⌉ elements except the last ones, which can be shorter or empty. Sample:3.
Return the collection split into count groups of consecutive elements. See partition for splitting into fixed-size chunks.
chunk([1, 2, 3, 4, 5, 6], 3)
// ➔ [[1,2],[3,4],[5,6]]
To split a collection into parts of a given size, use
partition. From a string, each group is a string.
chunk([1, 2, 3, 4, 5], 2)
// ➔ [[1,2,3],[4,5]]
chunk("abcdef", 2)
// ➔ ["abc","def"]
MathJSON: Chunk
["Chunk", xs, count].
["Chunk", ["List", 1, 2, 3, 4, 5], 2]
// ➔ ["List", ["List", 1, 2, 3], ["List", 4, 5]]
chunkBy
((xs: S, key: (character) any -> unknown) -> list<string> where S: string) & ((xs: indexed_collection<T>, key: (T) any -> unknown) -> list<list<T>> where T: any)
xs— The list or string to split. Sample:[1, 3, 2, 4, 5].key— The function of each element; a new run starts where its value changes. Sample:x => x % 2.
Split the collection into maximal runs of consecutive elements over which the key function yields the same value.
Returns a list of lists. Unlike groupBy, only adjacent elements are grouped, so a key value that recurs after a different run starts a new chunk.
chunkBy([1, 3, 2, 4, 5], x => x % 2)
// ➔ [[1,3],[2,4],[5]]
From a string, each run is a string, so the result is a list<string>. The
same rule holds for slidingWindow, permutations and combinations.
chunkBy([1, 1, 2, 2, 2, 1], x => x)
// ➔ [[1,1],[2,2,2],[1]]
chunkBy("aabbc", x => x)
// ➔ ["aa","bb","c"]
MathJSON: ChunkBy
["ChunkBy", xs, key].
["ChunkBy", ["List", 1, 1, 2, 2, 2, 1], ["Function", "x", "x"]]
// ➔ ["List", ["List", 1, 1], ["List", 2, 2, 2], ["List", 1]]
closed
MathJSON Closed · (number) -> number
- argument 1 — The endpoint to include in the interval. Sample:
1.
Closed(x): the endpoint x of an Interval, marked as included. A marker with no value of its own; Interval normalizes it away.
1 in interval(0, closed(1))
// ➔ true
complement
(set<any>+) -> set
- arguments 1, … — The sets: the first one, then the sets whose elements are removed from it. Sample:
Set(1, 2, 3, 4).
Return the elements of the first set that are not in any of the subsequent sets.
listFrom(complement(set(1, 2, 3, 4), set(2, 4)))
// ➔ [1,3]
MathJSON: Complement • LaTeX: ^{\complement}
complexNumbers
constant set<complex>
The set of all finite complex numbers.
2 + 3i in complexNumbers
// ➔ true
MathJSON: ComplexNumbers • LaTeX: \mathbb{C}
contains
(xs: collection<any>, element: any) -> boolean
xs— The collection to search; the elements of a string are its characters. Sample:[1, 2, 3].element— The value to find, compared structurally. Sample:2.
Return True if the collection contains the given element (structural identity, like ===), False otherwise. An absent element is found where the same marker sits: contains([1, NaN], NaN) is True.
Equivalent to any(xs, (e) => e === v); use any to test an arbitrary predicate instead of a specific value.
contains([1, 2, 3], 2)
// ➔ true
Over a list or a tuple, the comparison is structural identity, as for
isSame. To test a predicate instead of one
value, use any.
A symbol with no value is a different expression from a number, even when
the symbol could hold that number, so contains answers False. To leave
the answer open until the symbols have values, use in
(Element), which stays unevaluated:
contains([a, b], 3)
// ➔ false
3 in [a, b]
// ➔ Element(3, [a,b])
Over a set, contains is a membership test, as in is: two numbers with no
unknowns are compared by exact value, with no tolerance, and a value with an unknown leaves the answer open.
[contains(set(1, 2, 3), e), contains(set(1, 2, 3), 2.0)]
// ➔ [false,true]
contains(set(1, 2, 3), x)
// ➔ Contains(Set(1, 2, 3), x)
contains tests for one element. To test for a run of several consecutive
elements, a sublist or a substring, use
containsSequence.
[contains("abc", "ab"), containsSequence("abc", "ab")]
// ➔ [false,true]
MathJSON: Contains
["Contains", xs, value].
["Contains", ["List", 5, 2, 10, 18], 10]
// ➔ "True"
["Contains", ["Set", 1, 2, 3], "x"]
// ➔ ["Contains", ["Set", 1, 2, 3], "x"]
containsSequence
(xs: indexed_collection<T>, needle: indexed_collection<T>) -> boolean where T
xs— The list or string to search. Sample:[1, 2, 3, 4].needle— The run of consecutive elements to find; an empty needle is always found. Sample:[2, 3].
Return True when needle occurs as a contiguous subsequence of the indexed collection.
Unlike contains, which tests membership of a single element, the needle is read as a sequence: containsSequence("abc", "ab") is True while contains("abc", "ab") is False.
containsSequence([1, 2, 3, 4], [2, 3])
// ➔ true
For a needle that is not empty, containsSequence is True when
rangeOf does not answer Missing. An empty needle is True:
the empty sequence is a subsequence of every collection. This is the one
rule that differs from rangeOf, which must reject an empty needle because
it returns a span.
containsSequence([1, 2, 3], [3, 2])
// ➔ false
containsSequence([1, 2, 3], [])
// ➔ true
containsSequence is not contains, which tests for one
element: contains("abc", "ab") is False, because "ab" is not one of
the characters of the string.
[containsSequence("abc", "bc"), containsSequence("abc", "ac")]
// ➔ [true,false]
containsSequence("abc", "")
// ➔ true
MathJSON: ContainsSequence
["ContainsSequence", xs, needle].
["ContainsSequence", ["List", 1, 2, 3], ["List", 2, 3]]
// ➔ "True"
["ContainsSequence", {str: "abc"}, {str: "bc"}]
// ➔ "True"
count
(xs: collection<any>, element: any?, levels: any?) -> infinity | integer
xs— The collection; with no other argument, the result is its number of elements,+oofor an unbounded one. Sample:[1, 2, 1, 3, 1].element— The value to count, compared structurally, or a predicate that each counted element satisfies. Sample:1.levels— The levels of a nested list to count in, with a value to count:nfor the levels 1 ton,[n]for the levelnonly,[from, to]for a range. Sample:2.
count(xs): the number of elements in the collection.
count(xs, v): how many elements are structurally the same as v.
count(xs, p): how many elements satisfy the predicate p.
count([1, 2, 1, 3, 1], 1)
// ➔ 3
With one argument, count is the number of elements, as
length is. Of a matrix (a list of lists), it is the number of
rows.
[count([[1, 2], [3, 4]]), count(set(1, 2)), count("abc")]
// ➔ [2,2,3]
Counting a value
With a second argument that is not a function, count is the number of
elements that are the same as that value. The comparison is structural
identity, as for isSame and
contains. Numbers compare by exact value, so 0.5 counts as
an occurrence of 1/2.
[count([1, 2, 2, 3, 2], 2), count([1, 2, 2, 3], 5)]
// ➔ [3,0]
count([1/2, 0.5, 1], 1/2)
// ➔ 2
A third argument counts the parts equal to the value at some levels of a
nested collection: n is the levels 1 to n, [n] the level n only,
[from, to] a range of levels, and oo every level.
count([[1, 1], 1], 1, 2)
// ➔ 3
[count([[1, [1]], 1], 1, [2]), count([[1, [1]], 1], 1, oo)]
// ➔ [1,3]
Counting with a predicate
With a second argument that is a function, count is the number of
elements that satisfy it. The predicate must return True or False for
each element, as for filter. An expression with _ is a
predicate; a value without _, such as True, is counted as a value.
count([1, 2, 3, 4, 5], _ > 2)
// ➔ 3
count([True, False, True], True)
// ➔ 2
The forms with two or three arguments need a finite collection; over an
unbounded one, count stays unevaluated.
count(1..oo, 2)
// ➔ Count(1..oo, 2)
MathJSON: Count
["Count", xs], ["Count", xs, value], ["Count", xs, value, levels],
["Count", xs, predicate].
["Count", ["List", 1, 2, 2, 3, 2], 2]
// ➔ 3
["Count", ["List", ["List", 1, 1], 1], 1, 2]
// ➔ 3
["Count", ["List", 1, 2, 3, 4, 5], ["Greater", "_", 2]]
// ➔ 3
In LaTeX, |S|, \#S, \operatorname{card}(S) and \operatorname{Card}(S)
of a set or a string parse to ["Count", "S"], and Count of a set or a
string serializes as |S|: ["Count", ["Set", 1, 2]] is
\vert\lbrace1, 2\rbrace\vert. Of a list, |L| is the element-wise absolute
value, and \# alone is the symbol hash.
countIf
(xs: collection<T>, predicate: (T) any -> boolean) -> integer where T
xs— The collection whose elements are counted. Sample:[1, 4, 9, 16].predicate— The test that each counted element passes. Sample:x => x > 5.
Return the number of elements in the collection satisfying the predicate.
countIf([1, 4, 9, 16], x => x > 5)
// ➔ 2
MathJSON: CountIf
["CountIf", xs, predicate].
["CountIf", ["List", 5, 2, 10, 18], ["Greater", "_", 5]]
// ➔ 2
cycle
(list<any>) -> list
- argument 1 — The list to repeat; an empty list gives an empty list. Sample:
[1, 2].
Produce an infinite sequence by cycling through the elements of a finite collection.
take(cycle([1, 2]), 5)
// ➔ [1,2,1,2,1]
The seed collection must be finite. Use take to get a finite
number of elements.
cycle(1..3)
// ➔ [1,2,3,1,2,...]
take(cycle(1..3), 7)
// ➔ [1,2,3,1,2,3,1]
MathJSON: Cycle
["Cycle", seed].
["Take", ["Cycle", ["List", 5, 7, 2]], 5]
// ➔ ["List", 5, 7, 2, 5, 7]
dedup
(collection<any>) -> collection
- argument 1 — The collection or string to collapse. Sample:
[1, 1, 2, 2, 1].
Return the collection with consecutive duplicate elements collapsed to a single element.
Only immediately-adjacent equal elements are removed; unlike unique, a value that recurs after a different element is kept.
dedup([1, 1, 2, 2, 1])
// ➔ [1,2,1]
dedup is lazy: the elements are computed when they are read. A string
gives a string.
dedup("aabba")
// ➔ "aba"
MathJSON: Dedup
["Dedup", xs].
["Dedup", ["List", 1, 1, 2, 2, 1]]
// ➔ ["List", 1, 2, 1]
deleteAt
((xs: T, index: integer) -> T where T: string) & ((xs: indexed_collection<T>, index: integer) -> list<T> where T: any) & ((xs: dictionary<V>, key: string) -> dictionary<V> where V: any)
xs— The list, string, dictionary or record to copy without one element. Sample:[1, 2, 3, 4].index— The 1-based position of the element to remove; a negative index counts from the end, and 0 or an index out of range leaves the call unevaluated. Sample:2.key— The key of the entry to remove; a key that is not there gives the value unchanged. Sample:"b".
Return a copy of the indexed collection with the element at the 1-based index removed.
A negative index counts from the end. An out-of-range, zero, or non-integer index leaves the expression unevaluated.
Deleting from a string yields a string.
On a dictionary or a record, deleteAt(d, key) returns a copy without the entry of the string key; d does not change. A key that is not there gives the value unchanged. The type of a record loses the field (record{a: integer, b: string?} gives record{a: integer}); with a key known only at evaluation, every field of the record becomes optional.
A value of a declared (nominal) record type is not a collection, so deleteAt refuses it, as At does.
deleteAt([1, 2, 3, 4], 2)
// ➔ [1,3,4]
deleteAt({a -> 1, b -> "x"}, "b")
// ➔ {"a" -> 1}
The collection is not changed. An index out of range, or a symbol, leaves the call unevaluated. The result has the kind of the source, so deleting from a string gives a string.
deleteAt([1, 2, 3], 7)
// ➔ DeleteAt([1,2,3], 7)
[deleteAt("abcdef", 2), deleteAt("abcdef", -1)]
// ➔ ["acdef","abcde"]
On a dictionary, a key that is not there gives the dictionary unchanged. A record type loses the field.
deleteAt({a -> 1, b -> "x"}, "zz")
// ➔ {"a" -> 1, "b" -> "x"}
type(deleteAt({a -> 1, b -> "x"}, "b"))
// ➔ TypeFrom("record{a: integer}")
MathJSON: DeleteAt
["DeleteAt", xs, index], ["DeleteAt", dictionary, key].
["DeleteAt", ["List", 1, 2, 3], -1]
// ➔ ["List", 1, 2]
["DeleteAt", {dict: {a: 1, b: "x"}}, {str: "b"}]
// ➔ {dict: {a: 1}}
Dictionary
(tuple<string, unknown>*) -> dictionary
A collection of key -> value entries with string keys ({x -> 1, y -> 2} in Epsil).
{"a" -> 1, "b" -> 2}["b"]
// ➔ 2
dictionaryFrom
(collection<any>) -> dictionary
- argument 1 — The (key, value) pairs; a later pair with the same key replaces an earlier one. Sample:
[("a", 1), ("b", 2)].
Create a dictionary from the elements of a collection of (key, value) pairs.
dictionaryFrom([("a", 1), ("b", 2)])
// ➔ {"a" -> 1, "b" -> 2}
The collection must be a finite collection of (key, value) pairs, each key
a string. When several pairs have the same key, the last one wins.
dictionaryFrom([("a", 1), ("a", 9), ("b", 2)])
// ➔ {"a" -> 9, "b" -> 2}
This is how a dictionary literal with spread entries is evaluated: the
entries are joined and passed to dictionaryFrom, so a later entry,
written or spread, replaces an earlier one. {->, ...d1, ...d2} merges two
dictionaries. The same key written twice in one literal is an error instead.
let defaults = {"verbose" -> False, "depth" -> 2}
{...defaults, "verbose" -> True}
// ➔ {"verbose" -> true, "depth" -> 2}
{"a" -> 1, "a" -> 2}
// ➔ error: duplicate dictionary key: a
There is no recordFrom: a record and a dictionary differ only in their
type. The type of a dictionaryFrom call is dictionary; a literal with
the same entries is a record.
type(dictionaryFrom([("a", 1), ("b", "x")]))
// ➔ TypeFrom("dictionary")
type({"a" -> 1, "b" -> "x"})
// ➔ TypeFrom("record{a: integer, b: string}")
MathJSON: DictionaryFrom
["DictionaryFrom", pairs]. A Dictionary literal with ["Spread", d]
entries is evaluated as a DictionaryFrom of the joined entries.
["DictionaryFrom", ["List", ["Tuple", "'a'", 1], ["Tuple", "'b'", 2]]]
// ➔ {"dict": {"a": 1, "b": 2}}
differences
(indexed_collection<any>) -> indexed_collection
- argument 1 — The list of numbers; a list of one element gives an empty list. Sample:
[1, 4, 9, 16].
Return the successive differences of a collection: a collection whose k-th element is x(k+1) − xk, of length one less than the input.
differences([1, 4, 9, 16])
// ➔ [3,5,7]
The differences are exact: integers and rationals stay exact. differences
is lazy, so it also applies to an infinite collection.
differences([1/2, 1/3, 1/4])
// ➔ [-1/6,-1/12]
take(differences(1..oo), 3)
// ➔ [1,1,1]
MathJSON: Differences
["Differences", xs].
["Differences", ["List", 1, 4, 9, 16]]
// ➔ ["List", 3, 5, 7]
drop
((xs: T, count: number) -> T where T: string) & ((xs: indexed_collection<T>, count: number) -> list<T> where T: any)
xs— The list or string. Sample:[1, 2, 3, 4, 5].count— The number of elements to drop; a negative count drops the last elements, and a count past the length gives an empty result. Sample:2.
Return the indexed collection without its first count elements.
A negative count counts from the end: drop(xs, -n) is the collection without its last n elements.
A count past the length is clamped: the result is empty.
drop([1, 2, 3, 4, 5], 2)
// ➔ [3,4,5]
drop([1, 2, 3, 4, 5], -2)
// ➔ [1,2,3]
A count of 0 gives the whole collection, and a count past the length, in either direction, gives the empty collection. Of a string, the result is a string.
drop([5, 2, 10, 18], -10)
// ➔ []
drop("hello", -2)
// ➔ "hel"
A negative count needs the length of the collection. When the length is not known or is infinite, the expression stays unevaluated. A positive count applies to an infinite collection too.
drop(1..oo, -2)
// ➔ Drop(1..oo, -2)
drop(1..oo, 2)
// ➔ [3,4,5,6,7,...]
See take for the first n elements.
MathJSON: Drop
["Drop", xs, n].
["Drop", ["List", 5, 2, 10, 18], 2]
// ➔ ["List", 10, 18]
["Drop", ["List", 5, 2, 10, 18], 10]
// ➔ ["List"]
dropWhile
(xs: indexed_collection<T>, predicate: (T) any -> boolean) -> indexed_collection where T
xs— The collection whose leading elements are dropped. Sample:[1, 2, 3, 10, 4].predicate— The test of the leading elements; dropping stops at the first element that fails it. Sample:x => x < 5.
Return the collection with its leading elements for which the predicate returns True removed; the remaining elements are returned unfiltered.
dropWhile([1, 2, 3, 10, 4], x => x < 5)
// ➔ [10,4]
dropWhile is lazy. Once an element fails the predicate, the predicate is not
applied again: the rest of the collection is returned as it is.
dropWhile([1, 2, 3, 10, 1], x => x < 5)
// ➔ [10,1]
take(dropWhile(1..oo, x => x < 4), 3)
// ➔ [4,5,6]
See takeWhile for the leading elements.
MathJSON: DropWhile
["DropWhile", xs, predicate].
["DropWhile", ["List", 1, 2, 3, 10, 1], ["Function", ["Less", "x", 5], "x"]]
// ➔ ["List", 10, 1]
Element
(any, any, boolean?) -> boolean
Test whether a value is an element of a collection. Optional third argument is a boolean expression (condition) for filtered iteration in Sum/Product.
Element supports two modes of operation:
- Set membership: Element(3, [List, 1, 2, 3]) checks if 3 is in the list
- Type-style membership: Element(x, integer) checks if x has type integer
Type-style membership works with:
- Mathematical sets: Integers, RealNumbers, ComplexNumbers, etc.
- Type names: integer, rational, real, number, positive_integer, etc.
- Invalid type names remain unevaluated (e.g., Element(2, "Booleans"))
3 in set(1, 2, 3)
// ➔ true
MathJSON: Element • LaTeX: \in
emptySet
constant set
The empty set, a set containing no elements.
isEmpty(emptySet)
// ➔ true
MathJSON: EmptySet • LaTeX: \emptyset
endsWith
(xs: indexed_collection<T>, suffix: indexed_collection<T>) -> boolean where T
xs— The list or string to test. Sample:[1, 2, 3].suffix— The run of elements that must end the collection. Sample:[2, 3].
Return True when the indexed collection ends with suffix as a contiguous subsequence.
On a string the suffix is matched character by character, so a suffix that would begin inside a grapheme cluster does not match. An empty suffix matches everything.
endsWith([1, 2, 3], [2, 3])
// ➔ true
An empty suffix is True. endsWith reads the end of the collection, so it
needs a collection of known length; otherwise it stays unevaluated.
endsWith(1..oo, [2, 3])
// ➔ EndsWith(1..oo, [2,3])
A suffix that would begin inside a grapheme cluster does not match: the only
character of "e\u{301}" is é, which is not the combining accent.
endsWith("hello", "lo")
// ➔ true
endsWith("e\u{301}", "\u{301}")
// ➔ false
MathJSON: EndsWith
["EndsWith", xs, suffix].
["EndsWith", ["List", 1, 2, 3], ["List", 2, 3]]
// ➔ "True"
["EndsWith", {str: "hello"}, {str: "lo"}]
// ➔ "True"
extendedComplexNumbers
constant set<complex | infinity>
The set of all complex numbers, including infinities.
complexInfinity in extendedComplexNumbers
// ➔ true
MathJSON: ExtendedComplexNumbers • LaTeX: \overline\C
extendedIntegers
constant set<integer | signed_infinity>
The set of all integers, including infinities.
Infinity in extendedIntegers
// ➔ true
MathJSON: ExtendedIntegers • LaTeX: \overline\Z
extendedRationalNumbers
constant set<rational | signed_infinity>
The set of all rational numbers, including infinities.
-Infinity in extendedRationalNumbers
// ➔ true
MathJSON: ExtendedRationalNumbers • LaTeX: \overline\Q
extendedRealNumbers
constant set<real | signed_infinity>
The set of all real numbers, including infinities.
-Infinity in extendedRealNumbers
// ➔ true
MathJSON: ExtendedRealNumbers • LaTeX: \overline\R
field
(value: any, field: string) -> unknown
value— The record, the dictionary, or the value of a nominal type with named fields. Sample:{x -> 1, y -> 2}.field— The name of the field. Sample:"y".
Return the named field of a value: p.x in Epsil.
On a record or dictionary value, field(d, "x") behaves exactly as d["x"] (At semantics, including the absence marker for a key a dictionary may not have).
On a value of a NOMINAL type whose definition body has named fields (a record body, or a named-tuple body), the field is resolved through the type definition — the sanctioned accessor window of the nominal-types design (D6/§4.5b D16). This does not make the value a collection: first(p) and p["x"] keep rejecting.
A field name that is not in a record/named-tuple definition is a static defect (the result type is error); on an unknown-typed operand the expression stays symbolic.
Record types are closed: on an operand of a record type, a field name that the type does not list is refused when the expression is boxed (unknown-field). An optional field (b: string?) that the value leaves out reads as the absent value of its type: missing, or NaN for a numeric field.
{x -> 1, y -> 2}.y
// ➔ 2
On a value of a nominal type whose definition has named fields, a record body
or a named-tuple body, the field is read through the definition. This does not
make the value a collection: first(p) and p["x"] are still rejected. A
name that is not a field of the definition is an error.
type Circle = tuple<radius: number>
Circle(2).radius
// ➔ 2
type Circle = tuple<radius: number>
Circle(2).area
// ➔ error: Runtime error: `area` is not a field at `Circle(2)`
type Circle = tuple<radius: number>
first(Circle(2))
// ➔ error: Type error: expected `indexed_collection`, got `Circle` at `Circle(2)` in `first(Circle(2))`
On an operand whose type is unknown, Field stays symbolic:
q.x
// ➔ Field(q, "x")
MathJSON: Field
["Field", value, field]. On a record or a dictionary,
["Field", d, "'x'"] is ["At", d, "'x'"], including the absence marker for
a key that the dictionary does not have.
["Field", ["Dictionary", ["KeyValuePair", "'a'", 10]], "'a'"]
// ➔ 10
filter
(xs: collection<T>, predicate: (T) any -> boolean) -> collection where T
xs— The collection to filter. Sample:[1, 2, 3, 4, 5, 6].predicate— The test that each kept element passes. Sample:x => x > 2.
Return the elements of the collection for which the predicate function returns True.
Equivalent to [x for x in xs if p(x)].
The collection is the first argument and the predicate the second. map has the opposite order, map(f, xs), because it takes any number of collections after its function.
filter([1, 2, 3, 4, 5, 6], x => x % 2 == 0)
// ➔ [2,4,6]
An indexed collection (a list, a tuple or a range) gives a list of the
elements that are kept, never the shape or the length of the source, since
filtering changes the length. A set gives a set.
[filter((5, 2, 10), _ < 10), filter(1..6, isPrime)]
// ➔ [[5,2],[2,3,5]]
filter(set(5, 2, 10, 18), _ < 10)
// ➔ Set(2, 5)
The predicate must return a boolean:
filter([1, 2, 3], x => x)
// ➔ error: Type error: expected `(integer) any -> boolean`, got `(x: integer) -> integer` at `Function(do {x}, x)` in `filter([1, 2, 3], Function(x, x))`
MathJSON: Filter
["Filter", xs, predicate].
["Filter", ["List", 5, 2, 10, 18], ["Less", "_", 10]]
// ➔ ["List", 5, 2]
find
(xs: indexed_collection<T>, predicate: (T) any -> boolean) -> any where T: any
xs— The collection to search, from its first element. Sample:[1, 4, 9, 16].predicate— The test that the element found passes. Sample:x => x > 5.
Return the first element of the collection satisfying the predicate. When no element satisfies it, return the absent value of the domain of the elements: NaN for numbers, a point whose coordinates are all NaN for points, and missing otherwise.
find([1, 4, 9, 16], x => x > 5)
// ➔ 9
When no element satisfies the predicate, the result is the value that a read
out of range of the same collection gives. Use
Coalesce to give a default.
find([5, 2, 10, 18], _ > 100)
// ➔ NaN
find([(1, 2), (3, 4)], p => first(p) > 9)
// ➔ (NaN, NaN)
find(["a", "b"], s => s == "z")
// ➔ missing
Coalesce(find([5, 2, 10, 18], _ > 100), 0)
// ➔ 0
MathJSON: Find
["Find", xs, predicate].
["Find", ["List", 5, 2, 10, 18], ["Greater", "_", 9]]
// ➔ 10
["Find", ["List", 5, 2, 10, 18], ["Greater", "_", 100]]
// ➔ "NaN"
first
(xs: indexed_collection<any>, default: any?) -> any
xs— The list or string. Sample:[7, 8, 9].default— The result for an empty collection; without it, an empty collection gives the absent value of its elements,NaNfor numbers andMissingotherwise. Sample:0.
The first element of a collection.
first([7, 8, 9])
// ➔ 7
first(xs) is xs[1]. With a second argument, that argument is the value
when the collection is empty; without it, the value is the absence marker of
At.
first((x, y))
// ➔ x
first([], 0)
// ➔ 0
MathJSON: First
["First", xs], ["First", xs, default].
["First", ["List", 5, 2, 10, 18]]
// ➔ 5
["First", ["List"], 0]
// ➔ 0
flatMap
(xs: collection<T>, mapping: (T) any -> U) -> list where T, U
xs— The collection to map over. Sample:[1, 2, 3].mapping— The function applied to each element; a collection result other than a string is spliced into the result, and a string or any other value is kept as one element. Sample:x => [x, x].
Map a function over a collection and concatenate the results into a single list, splicing collection-valued results and keeping scalar results as single elements.
The collection is the first argument, as for filter. map has the opposite order, map(f, xs), because it takes any number of collections after its function.
flatMap([1, 2, 3], x => [x, x])
// ➔ [1,1,2,2,3,3]
A result that is a collection is spliced into the output. A result that is not a collection is kept as one element; it is not an error.
flatMap([1, 2, 3], x => 1..x)
// ➔ [1,1,2,1,2,3]
flatMap([1, 2, 3], x => 2 * x)
// ➔ [2,4,6]
flatMap is lazy: the elements are computed when they are read.
MathJSON: FlatMap
["FlatMap", xs, f].
["FlatMap", ["List", 1, 2, 3], ["Function", ["List", "x", "x"], "x"]]
// ➔ ["List", 1, 1, 2, 2, 3, 3]
fold
(reducer: (unknown, T) any -> unknown, initial: value, xs: collection<T>) -> value where T
reducer— The function of the accumulator and the next element, which returns the new accumulator. Sample:(acc, x) => acc + x.initial— The accumulator before the first element, and the result for an empty collection. Sample:0.xs— The collection, read from its first element to its last. Sample:[1, 2, 3, 4].
Fold a collection to a single value, applying a binary function f(accumulator, element) left to right from an initial value.
The function is the first argument and the collection the last. reduce does the same with the collection first: reduce(xs, f, initial).
fold((a, b) => a + b, 0, [1, 2, 3, 4])
// ➔ 10
fold is reduce with the function first. Without an initial
value, it starts from the first element: fold(f, xs) is reduce(xs, f).
fold((acc, x) => acc * 10 + x, 0, [1, 2, 3])
// ➔ 123
fold(max, [3, 9, 2])
// ➔ 9
MathJSON: Fold
["Fold", f, initial, xs], ["Fold", f, xs].
["Fold", "Add", 0, ["List", 1, 2, 3, 4]]
// ➔ 10
["Fold", "Add", ["Sqrt", 2], ["List"]]
// ➔ ["Sqrt", 2]
groupBy
(xs: collection<T>, key: (T) any -> unknown) -> dictionary<list> where T
xs— The collection to group. Sample:[1, 2, 3, 4, 5].key— The function whose value names the group of an element; the keys of the dictionary are its values as strings. Sample:x => x % 2.
Partition the collection into a dictionary of lists based on the key returned by the function.
groupBy(["apple", "fig", "pear", "kiwi"], length)
// ➔ {"3" -> ["fig"], "4" -> ["pear","kiwi"], "5" -> ["apple"]}
The keys of a dictionary are strings, so the key that the function returns is converted to a string.
groupBy([1, 2, 3, 4], isEven)
// ➔ {"False" -> [1,3], "True" -> [2,4]}
MathJSON: GroupBy
["GroupBy", xs, key].
["GroupBy", ["List", 1, 2, 3, 4], ["IsEven", "_"]]
// ➔ {"dict": {"False": [1, 3], "True": [2, 4]}}
imaginaryNumbers
constant set<imaginary>
The set of all imaginary numbers.
3i in imaginaryNumbers
// ➔ true
MathJSON: ImaginaryNumbers • LaTeX: \imaginaryI\R
indexOf
(xs: indexed_collection<any>, element: any) -> integer
xs— The list or string to search; the elements of a string are its characters. Sample:[10, 20, 30].element— The value to find, compared structurally. Sample:20.
Return the 1-based index of the first occurrence of value in collection, or 0 if not found. The comparison is structural, so an absent value is found where the same marker sits: indexOf([1, NaN], NaN) is 2. Stays unevaluated when the collection cannot be searched (a symbol with no value, an unbounded source with no match).
indexOf([10, 20, 30], 20)
// ➔ 2
indexOf searches for one element, so in a list of lists the value is a
whole row. To search for a run of several consecutive elements, a sublist or
a substring, use rangeOf.
[indexOf([5, 2, 10, 2], 2), indexOf([5, 2, 10, 2], 42)]
// ➔ [2,0]
indexOf([[1, 2], [3, 4]], [3, 4])
// ➔ 2
MathJSON: IndexOf
["IndexOf", xs, value].
["IndexOf", ["List", 5, 2, 10, 2], 2]
// ➔ 2
indexWhere
(xs: indexed_collection<T>, predicate: (T) any -> boolean) -> integer where T
xs— The collection to search. Sample:[1, 4, 9, 16].predicate— The test applied to each element, in order. Sample:x => x > 5.
Return the 1-based index of the first element satisfying the predicate, or 0 if not found. Stays unevaluated when the collection cannot be searched (a symbol with no value, an unbounded source with no match).
indexWhere([1, 4, 9, 16], x => x > 5)
// ➔ 3
[indexWhere([5, 2, 10, 18], _ > 9), indexWhere([5, 2, 10, 18], _ > 99)]
// ➔ [3,0]
MathJSON: IndexWhere
["IndexWhere", xs, predicate].
["IndexWhere", ["List", 5, 2, 10, 18], ["Greater", "_", 9]]
// ➔ 3
insert
(xs: indexed_collection<T>, index: integer, element: T) -> list<T> where T: any
xs— The collection; a string gives a list of its characters. Sample:[1, 2, 4].index— The 1-based position of the inserted element, from 1 to n + 1; a negative index counts from the end, -1 appending. Sample:3.element— The value to insert. Sample:3.
Return a copy of the indexed collection with element inserted before the 1-based index.
index may range from 1 to n+1 (n+1 appends). A negative index counts from the end, with -1 appending at the end (Elixir semantics).
An out-of-range, zero, or non-integer index leaves the expression unevaluated.
insert([1, 2, 4], 3, 3)
// ➔ [1,2,3,4]
The element at the index and the elements after it move one position to the
right; the index n + 1 appends. A negative index counts from the end:
-1 appends, and -2 inserts before the last element.
[insert([1, 2, 3], 2, 99), insert([1, 2, 3], 4, 99)]
// ➔ [[1,99,2,3],[1,2,3,99]]
[insert([1, 2, 3], -1, 99), insert([1, 2, 3], -2, 99)]
// ➔ [[1,2,3,99],[1,2,99,3]]
The collection is not changed. An index out of range, or a symbol, leaves the call unevaluated.
insert([1, 2, 3], 9, 99)
// ➔ Insert([1,2,3], 9, 99)
MathJSON: Insert
["Insert", xs, index, value].
["Insert", ["List", 1, 2, 3], 2, 99]
// ➔ ["List", 1, 99, 2, 3]
integers
constant set<integer>
The set of all finite integers.
-7 in integers
// ➔ true
MathJSON: Integers • LaTeX: \mathbb{Z}
intersection
(any+) -> set
- arguments 1, … — A set or another finite collection, whose duplicate elements count once. Sample:
Set(1, 2, 3).
Return the intersection of one or more collections as a set.
intersection(set(1, 2, 3), set(2, 3, 4))
// ➔ Set(2, 3)
MathJSON: Intersection • LaTeX: \cap
interval
(start: number, end: number) -> set<real>
start— The lower endpoint, included unless it is wrapped inOpen; it may be-oo. Sample:0.end— The upper endpoint, included unless it is wrapped inOpen; it may be+oo. Sample:1.
A set of real numbers between two endpoints. The endpoints may or may not be included.
0.5 in interval(0, 1)
// ➔ true
An interval is a set of real numbers. Each bound is included unless it is
wrapped in Open. Closed marks an included bound explicitly. An infinite
bound is never included: +oo is not a real number. The integers between two
bounds are a range instead, written a..b.
[0 in interval(0, 1), 1.5 in interval(1, 2), 1.5 in 1..2]
// ➔ [true,true,false]
[0 in interval(Open(0), 1), 1 in interval(0, Open(1))]
// ➔ [false,false]
[5 in interval(0, oo), oo in interval(0, oo)]
// ➔ [true,false]
type(interval(0, 1))
// ➔ TypeFrom("set<real>")
An interval cannot be enumerated. A quantifier over one is not decided by trying its elements: see Quantifier evaluation.
MathJSON: Interval
["Interval", a, b], with ["Open", a] or ["Closed", a] for a bound:
["Interval", ["Open", 0], 1] is the interval from 0 to 1 without 0. In
LaTeX, [a, b] is closed, (a, b) and ]a, b[ are open, and [a, b) and
(a, b] are half-open. See the notation table of the
Sets reference.
isEmpty
(collection<any>) -> boolean
- argument 1 — The collection or string to test. Sample:
[1, 2, 3].
Return True if the collection is empty, False otherwise.
isEmpty([])
// ➔ true
A symbol that is not known to be a collection leaves the answer open. A string is a collection of characters.
[isEmpty([5, 2, 10, 18]), isEmpty("Hello"), isEmpty("")]
// ➔ [false,false,true]
isEmpty(x)
// ➔ IsEmpty(x)
MathJSON: IsEmpty
["IsEmpty", xs].
["IsEmpty", ["List"]]
// ➔ "True"
iterate
(f: function, initial: any?) -> list
f— The function that computes each element from its 1-based index and the previous element, or from the previous element alone when it takes one argument. Sample:x => 2x.initial— The value before the first element,Nothingby default. Sample:1.
Produce an infinite sequence by repeatedly applying a function to the previous value, starting with an initial value.
The function is invoked as f(index, acc): index is the 1-based position of the element being produced, and acc is the previous element — the initial value when producing element 1. Element k is therefore f(k, element(k-1)).
A function whose type says it is UNARY is applied to the accumulator alone (iterate(2 * _, 1) produces [2, 4, 8, 16, …]); a statically-unknown arity keeps the two-argument form.
take(iterate(x => 2x, 1), 5)
// ➔ [2,4,8,16,32]
The initial value is not an element of the collection: element 1 is the
function applied to it. With no initial value, it is Nothing. Use
take to get a finite number of elements.
A function with two parameters receives the 1-based index and the previous
element; here the factorials. A function with one parameter, including the
_ shorthand, receives the previous element only.
take(iterate((n, acc) => n * acc, 1), 5)
// ➔ [1,2,6,24,120]
take(iterate(_ * 2, 1), 5)
// ➔ [2,4,8,16,32]
take(iterate(x => [x]), 2)
// ➔ [[nothing],[[nothing]]]
MathJSON: Iterate
["Iterate", f], ["Iterate", f, initial].
["Take", ["Iterate", ["Add", "_", 2], 7], 5]
// ➔ ["List", 9, 11, 13, 15, 17]
["Take", ["Iterate", ["Function", ["Multiply", "n", "acc"], "n", "acc"], 1], 5]
// ➔ ["List", 1, 2, 6, 24, 120]
join
((T+) -> T where T: string) & ((collection<any>*) -> collection)
- arguments 1, … — A collection or string whose elements are spliced into the result (strings alone give their concatenation), or another value, such as a tuple, added as one element. Sample:
"ab".
Join the elements of some collections into a flat collection.
A tuple operand is appended as a single element, not spliced.
A scalar operand is appended as a single element too: join([1, 2], 3) is [1, 2, 3].
When every operand is a string, the result is their concatenation as a string: join is the variadic string concatenation.
join([1, 2], [3, 4])
// ➔ [1,2,3,4]
join("ab", "cd")
// ➔ "abcd"
Collections are immutable: join returns a new collection and does not
change its arguments.
When the arguments are of different kinds, the result is a list of the elements of the first collection followed by those of the next ones. When any argument is a set, the result is a set, and an element that occurs more than once is kept once.
join([5, 2, 10, 18], [1, 2, 3])
// ➔ [5,2,10,18,1,2,3]
[join(set(1, 2), set(2, 3)), join(set(1, 2), [2, 3])]
// ➔ [Set(1, 2, 3),Set(1, 2, 3)]
The kind of the result depends on the arguments, not on the context. When one argument is not a string, a string argument contributes its characters.
join("ab", characters("cd"))
// ➔ ["a","b","c","d"]
To join the elements of one collection of strings into a string, with an
optional separator, use stringJoin.
When every argument is a string, the result is their concatenation, a string. The result is segmented again, so it can have fewer characters than the arguments together (see The re-segmentation caveat).
join("ab", "cd", "ef")
// ➔ "abcdef"
[join("e", "\u{301}"), length(join("e", "\u{301}"))]
// ➔ ["é",1]
String interpolation also concatenates a few strings: "\(a)\(b)". It
converts each value to text, where join concatenates strings only and
reads any other argument as a collection or an element.
join("ab", 1)
// ➔ ["a","b",1]
MathJSON: Join
["Join", xs, ys, …].
["Join", ["List", 5, 2, 10, 18], ["List", 1, 2, 3]]
// ➔ ["List", 5, 2, 10, 18, 1, 2, 3]
["Join", ["Set", 1, 2], ["List", 2, 3]]
// ➔ ["Set", 1, 2, 3]
["Join", {str: "ab"}, {str: "cd"}]
// ➔ "abcd"
["Join", {str: "ab"}, {str: "cd"}, {str: "ef"}]
// ➔ "abcdef"
["Join", {str: "ab"}, ["Characters", {str: "cd"}]]
// ➔ ["List", ["CharacterFrom", "'a'"], ["CharacterFrom", "'b'"], ["CharacterFrom", "'c'"], ["CharacterFrom", "'d'"]]
KeyValuePair
(key: string, value: T) -> tuple<string, T> where T
A key/value pair
Dictionary(KeyValuePair("a", 1), KeyValuePair("b", 2))
// ➔ {"a" -> 1, "b" -> 2}
keys
(dictionary<any>) -> list<string>
- argument 1 — The dictionary whose keys are listed. Sample:
{"a" -> 1, "b" -> 2}.
Return a list of the keys of a dictionary.
keys({"a" -> 1, "b" -> 2})
// ➔ ["a","b"]
The keys are in the iteration order of the dictionary, which is the order of the entries.
keys({"b" -> 1, "a" -> 2})
// ➔ ["b","a"]
MathJSON: Keys
["Keys", dictionary].
["Keys", ["Dictionary", ["KeyValuePair", "'a'", 1], ["KeyValuePair", "'b'", 2]]]
// ➔ ["List", "'a'", "'b'"]
last
(xs: indexed_collection<any>, default: any?) -> any
xs— The collection or string. Sample:[7, 8, 9].default— The value returned when the collection is empty; without it, an empty collection gives the absent value of its elements,NaNfor numbers andMissingotherwise. Sample:0.
The last element of a collection.
last([7, 8, 9])
// ➔ 9
last(xs) is xs[-1]. With a second argument, that argument is the value
when the collection is empty.
last([], 0)
// ➔ 0
MathJSON: Last
["Last", xs], ["Last", xs, default].
["Last", ["List", 5, 2, 10, 18]]
// ➔ 18
length
(any) -> infinity | integer
- argument 1 — The collection or string to measure. Sample:
[5, 6, 7].
Number of elements in a collection. Returns +oo for an infinite collection (an unbounded Range, integers, repeat(5), an interval), as count does, an incompatible-type error for an operand that is decidably not a collection, missing for an absent operand, and stays unevaluated for a collection whose size is not known (a filter over an infinite source).
length([5, 6, 7])
// ➔ 3
length("hello")
// ➔ 5
An unbounded collection has an infinite length, which is why the result type
is infinity | integer: the type integer is finite. A symbol with no
value stays unevaluated, and a value that is not a collection is an error.
length(1..oo)
// ➔ +oo
length(x)
// ➔ Length(x)
length(5)
// ➔ error: Runtime error: expected `collection`, got `5` at `5`
The length of Missing is Missing. A list that holds Missing keeps its
length.
length(Missing)
// ➔ missing
length([1, Missing])
// ➔ 2
For a collection, length and count give the same result.
MathJSON: Length
["Length", xs].
["Length", ["List", 5, 2, 10, 18]]
// ➔ 4
linspace
(start: number, end: number?, count: number?) -> list<number>
start— The first value; when it is the only argument, it is the last value and the sequence starts at 1. Sample:0.end— The last value. Sample:1.count— The number of values, 50 by default; 1 gives the start alone, and 0 or less an empty list. Sample:5.
A sequence of evenly spaced numbers between a start and end value, both endpoints included.
linspace(0, 1, 5)
// ➔ [0,0.25,0.5,0.75,1]
The name is short for "linearly spaced", after the
MATLAB function. It is
like Range, but the third argument is the number of elements instead of the
step. With no count, there are 50 elements. With one argument, the argument
is the upper bound and the lower bound is 1. The bounds can be descending.
count(linspace(3, 10))
// ➔ 50
take(linspace(2), 3)
// ➔ [1,1.0204081632653061,1.0408163265306123]
linspace(10, 1, 10)
// ➔ [10,9,8,7,6,5,4,3,2,1]
When a bound is an infinity or NaN, the samples cannot be computed and the
collection has no value: a read such as sum, count, max, an index or
Element stays unevaluated. With a count of 0 there are no samples, and the
collection is empty whatever the bounds.
count(linspace(0, oo, 3))
// ➔ Count(Linspace(0, +oo, 3))
count(linspace(0, oo, 0))
// ➔ 0
Compiled code gives NaN for a collection that has no value.
MathJSON: Linspace
["Linspace", upper], ["Linspace", lower, upper],
["Linspace", lower, upper, count].
["Linspace", 1, 10, 5]
// ➔ ["List", 1, 3.25, 5.5, 7.75, 10]
["Count", ["Linspace", 0, "PositiveInfinity", 0]]
// ➔ 0
List
(any*) -> list
An ordered collection of elements (a list).
List(1, 2, 3)
// ➔ [1,2,3]
A list is an indexed collection: its elements are in order, and an element
may be repeated. The type of a list is list<T>, where T is the type of its
elements; list is short for list<any>.
A vector is a list of numbers, and a matrix is a list of rows, each row a list of numbers. See the Linear Algebra library for the operations on vectors, matrices and tensors.
[[1, 2, 3], [4, 5, 6]]
// ➔ [[1,2,3],[4,5,6]]
Spread
...xs in a list literal splices the elements of the collection xs into the
list. An element that is not spread is kept as written, also when it is a
collection.
let xs = [1, 2]; [...take(xs, 1), 9, ...drop(xs, 1)]
// ➔ [1,9,2]
let xs = [1, 2]; [...xs, 1..3]
// ➔ [1,2,1..3]
A string is an indexed collection of characters, so it spreads into its
characters. A tuple is a unit and does not spread: convert it with
listFrom first. A scalar spreads as
itself.
[..."ab", "c"]
// ➔ ["a","b","c"]
[...(1, 2)]
// ➔ error: Runtime error: spread tuple at `(1, 2)`
[...5, 6]
// ➔ [5,6]
The list becomes a plain list when every spread operand is a finite collection and the total number of elements is within the materialization cap. An infinite operand keeps the list lazy:
[...(1..oo)]
// ➔ [1,2,3,4,5,...]
take([...(1..oo)], 3)
// ➔ [1,2,3]
A set literal accepts spread elements the same way, and removes duplicates. A dictionary literal merges spread dictionaries; on a key that occurs twice, the later entry wins.
set(1, ...[2, 2, 3])
// ➔ Set(1, 2, 3)
let d = {"a" -> 1, "b" -> 2}; {...d, "a" -> 5}
// ➔ {"a" -> 5, "b" -> 2}
MathJSON: List • LaTeX: [, ]
["List", ...elements]. A matrix is a List of rows:
["List", ["List", 1, 2, 3], ["List", 4, 5, 6], ["List", 7, 8, 9]].
A ["Spread", xs] element splices xs at canonicalization. A literal list
splices immediately; a symbolic or lazy operand lowers to the equivalent
ListJoin expression (a lone spread ["List", ["Spread", "xs"]] is
["ListJoin", "xs"]). When the literal is evaluated, the ListJoin becomes a
List once every spread operand is a finite collection and the total number
of elements is within ce.maxCollectionSize.
["List", ["Spread", ["List", 1, 2]], 3]
// ➔ ["List", 1, 2, 3]
["List", ["Spread", ["Range", 1, "PositiveInfinity"]]]
// ➔ ["ListJoin", ["Range", 1, "PositiveInfinity"]]
In LaTeX, a list is \lbrack 42, 3.14, x, y \rbrack, and an element
Nothing is \mathrm{Nothing}. A list of lists can also be written with a
; separator, \lbrack 1, 2, 3 ; 4, 5, 6 \rbrack, and a matrix with an
environment such as \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}. The
Delimiter function changes the delimiters and separator used to serialize a
list: ["Delimiter", xs, "<;>"] serializes ["List", 5, 2, 10, 18] as
\langle5;2;10;18\rangle.
listFrom
(value*) -> list
- arguments 1, … — A collection whose elements are added to the list in order, or another value that is added as one element. Sample:
[1, 2].
Create a list from the elements of a collection.
listFrom(set(1, 2), 3..4)
// ➔ [1,2,3,4]
Materializing a collection evaluates all its elements and stores them, so
the collection must be finite; over an infinite collection, listFrom stays
unevaluated. A string is a collection of characters.
listFrom(1..3)
// ➔ [1,2,3]
listFrom("abc")
// ➔ ["a","b","c"]
listFrom(1..oo)
// ➔ ListFrom(1..oo)
MathJSON: ListFrom
["ListFrom", xs].
["ListFrom", ["Range", 1, 3]]
// ➔ ["List", 1, 2, 3]
ListJoin
(collection<any>*) -> list
Join the elements of some collections into a list.
This is the canonical form of a list literal with a spread: [...a, 0] is ListJoin(a, [0]).
The result is a list whatever the kind of the operands: the elements of a set operand are included in the iteration order of the set, without deduplication.
A tuple operand is included as a single element, and so is a scalar operand.
ListJoin(set(3, 1), [0])
// ➔ [1,3,0]
map
(mapping: (T) any -> U, collection<T>+) -> indexed_collection where T, U
mapping— The function applied to each element, with one argument per collection. Sample:x => x^2.- arguments 2, … — A collection; with several, the result has the length of the shortest. Sample:
[1, 2, 3].
Return the collection where each element has been transformed by the mapping function.
With a single collection, equivalent to [f(x) for x in xs]. With multiple collections, combines them element-wise (like zipWith): Map(f, xs, ys) = [f(x1, y1), f(x2, y2), …], with the length of the shortest input.
The mapping function is the first argument, because map takes any number of collections after it. Most other operations that take a function, such as filter, flatMap and reduce, take one collection and put it first: filter(xs, p). map(xs, f) is an incompatible-type error.
map(x => x^2, [1, 2, 3])
// ➔ [1,4,9]
The function is the first argument, followed by one or more collections. With several collections, the function receives one element of each, and the result has the length of the shortest collection.
map(_ * 2, [5, 2, 10, 18])
// ➔ [10,4,20,36]
map((x, y) => x + y, [1, 2, 3], [10, 20])
// ➔ [11,22]
The number of arguments of a callback
The number of collections is the number of arguments the function receives.
A function literal, or a function with a known signature, whose number of
parameters cannot match it is a callback-arity error before evaluation.
map((p, q) => p + q, [1, 2, 3])
// ➔ error: Static error: Map calls its callback with 1 argument (each element of the collection); `(p, q) => p + q` declares 2 parameters in `map(Function(p + q, p, q), [1, 2, 3])`
The same rule holds for every function that takes a callback:
filter,any,all,count,takeWhile,flatMapand their kin pass one argument, the element.reduce,foldandscanpass two, the accumulator and the element.tabulatepasses one index per dimension.sortandorderingaccept a key (one argument) or a comparator (two), anditerateacceptsf(previous)orf(index, previous).
A function with no parameter, such as () => 42, is a constant and is
accepted at any number of arguments. To take a pair apart, use a tuple
parameter, ((p, q)) => …, which is one parameter.
map(() => 42, [1, 2])
// ➔ [42,42]
map(((p, q)) => p + q, [(1, 2), (3, 4)])
// ➔ [3,7]
Elements the function cannot accept
An element that the function cannot accept is kept as an error cell, and the
other elements are mapped. The epsil command line reports a result that
holds an error cell as a runtime error, so the example reads the cells one by
one.
let L = map(sqrt, [16, "banana"])
[L[1], isError(L[2])]
// ➔ [4,true]
An absent element (Missing) gives Missing under a numeric function, and
an incompatible-type error cell under a text function such as
toUpperCase. A function with a parameter declared as a number or a point
gives Missing for an absent element, without running its body.
map(x => sqrt(x), [16, Missing, 81])
// ➔ [4,missing,9]
map((x: integer) => x > 0, [1, Missing])
// ➔ [true,missing]
MathJSON: Map
["Map", f, xs], ["Map", f, xs, ys, …]. A tuple parameter is
["Function", body, ["Tuple", "p", "q"]].
["Map", ["Function", ["Add", "x", 1], "x"], ["List", 5, 2, 10, 18]]
// ➔ ["List", 6, 3, 11, 19]
["Map",
["Function", ["Add", "x", "y"], "x", "y"],
["List", 1, 2, 3],
["List", 10, 20, 30]]
// ➔ ["List", 11, 22, 33]
["Map", ["Function", ["Add", "p", "q"], "p", "q"], ["List", 1, 2, 3]]
// ➔ ["Error", ["ErrorCode", "'callback-arity'", ...]]
["Map", "ToUpperCase", ["List", "'a'", "Missing"]]
// ➔ ["List", "'A'", ["Error", ["ErrorCode", "'incompatible-type'", ...], "Missing"]]
maxBy
(xs: collection<T>, key: (T) any -> unknown) -> value where T
xs— The collection to search; the call stays unevaluated when it is empty or infinite. Sample:["pear", "fig", "apple"].key— The function of one element whose largest value selects the element; the first such element wins a tie. Sample:x => length(x).
Return the element of the collection that maximizes the given key function.
maxBy(["pear", "fig", "apple"], length)
// ➔ "apple"
The result is an element, not its key. On a tie, the first element wins.
maxBy stays unevaluated on an empty or infinite collection, or when a
comparison of keys cannot be decided.
[maxBy([-3, 1, -2], abs), maxBy([2, -2, 1], abs)]
// ➔ [-3,2]
maxBy([a, b], abs)
// ➔ MaxBy([a,b], abs)
MathJSON: MaxBy
["MaxBy", xs, key].
["MaxBy", ["List", -3, 1, -2], ["Function", ["Abs", "x"], "x"]]
// ➔ -3
MemberCall
(receiver: any, member: string, arguments: any*) -> unknown
Call the member name of a value with the value as its first argument: c.area(2) in Epsil.
A parse-level node. Canonicalization rewrites it to apply(field(c, "area"), 2) when the receiver's type declares a field area (a stored function is called), or to the bare protocol call area(c, 2) when area is a protocol function member; a canonical expression never contains it.
minBy
(xs: collection<T>, key: (T) any -> unknown) -> value where T
xs— The collection to search; the call stays unevaluated when it is empty or infinite. Sample:["pear", "fig", "apple"].key— The function of one element whose smallest value selects the element; the first such element wins a tie. Sample:x => length(x).
Return the element of the collection that minimizes the given key function.
minBy(["pear", "fig", "apple"], length)
// ➔ "fig"
The result is an element, not its key. On a tie, the first element wins.
minBy stays unevaluated on an empty or infinite collection, or when a
comparison of keys cannot be decided.
minBy([-3, 1, -2], abs)
// ➔ 1
MathJSON: MinBy
["MinBy", xs, key].
["MinBy", ["List", -3, 1, -2], ["Function", ["Abs", "x"], "x"]]
// ➔ 1
most
((T) -> T where T: string) & ((indexed_collection<T>) -> list<T> where T: any)
- argument 1 — The collection; an empty collection gives an empty result, and a string gives a string. Sample:
[7, 8, 9].
Return the collection without the last element.
If the collection has only one element, return an empty collection.
most([7, 8, 9])
// ➔ [7,8]
most(xs) is drop(xs, -1). Of a string, it is a string.
most("hello")
// ➔ "hell"
MathJSON: Most
["Most", xs].
["Most", ["List", 5, 2, 10, 18]]
// ➔ ["List", 5, 2, 10]
negativeIntegers
constant set<integer>
The set of all negative integers.
-3 in negativeIntegers
// ➔ true
MathJSON: NegativeIntegers • LaTeX: \mathbb{Z}_{<0}
negativeNumbers
constant set<real>
The set of all negative real numbers.
-0.5 in negativeNumbers
// ➔ true
MathJSON: NegativeNumbers • LaTeX: \mathbb{R}_{<0}
nonNegativeIntegers
constant set<integer>
The set of all non-negative integers.
0 in nonNegativeIntegers
// ➔ true
MathJSON: NonNegativeIntegers • LaTeX: \mathbb{N}
nonNegativeNumbers
constant set<real>
The set of all non-negative real numbers.
0 in nonNegativeNumbers
// ➔ true
MathJSON: NonNegativeNumbers • LaTeX: \mathbb{R}_{\geq0}
nonPositiveIntegers
constant set<integer>
The set of all non-positive integers.
0 in nonPositiveIntegers
// ➔ true
MathJSON: NonPositiveIntegers • LaTeX: \mathbb{Z}_{\le0}
nonPositiveNumbers
constant set<real>
The set of all non-positive real numbers.
0 in nonPositiveNumbers
// ➔ true
MathJSON: NonPositiveNumbers • LaTeX: \mathbb{R}_{\le0}
NotElement
(any, any) -> boolean
Test whether a value is not an element of a collection.
4 !in set(1, 2, 3)
// ➔ true
MathJSON: NotElement • LaTeX: \notin
NotSubset
(lhs: any, rhs: any) -> boolean
Test whether the first collection is not a strict subset of the second.
NotSubset(set(1, 4), set(1, 2, 3))
// ➔ true
MathJSON: NotSubset • LaTeX: \nsubset
NotSuperset
(lhs: any, rhs: any) -> boolean
Test whether the first collection is not a strict superset of the second.
NotSuperset(set(1, 2), set(1, 2, 3))
// ➔ true
MathJSON: NotSuperset • LaTeX: \nsupset
NotSupersetEqual
(lhs: any, rhs: any) -> boolean
Test whether the first collection is not a superset (possibly equal) of the second.
NotSupersetEqual(set(1, 2), set(1, 2, 3))
// ➔ true
numbers
MathJSON Numbers · constant set<number>
The set of all numbers.
2 + 3i in numbers
// ➔ true
open
MathJSON Open · (number) -> number
- argument 1 — The endpoint to exclude. Sample:
0.
Open(x): the endpoint x of an Interval, marked as excluded. A marker with no value of its own.
0 in interval(open(0), 1)
// ➔ false
ordering
(xs: indexed_collection<T>, order: (((T) any -> unknown) | ((any, any) any -> boolean | number))?) -> list<integer> where T: any
xs— The collection to sort. Sample:[30, 10, 20].order— A key function of one element, or a comparison of two elements (true or a negative number when the first comes first); by default the elements in ascending order. Sample:x => -x.
Return the indexes that would sort the collection.
ordering([30, 10, 20])
// ➔ [2,3,1]
The optional function is a key or a comparator, as for sort.
Indexing the collection with its ordering gives the sorted collection: an
index can be a list of indexes.
ordering(["pear", "fig", "apple"], length)
// ➔ [2,1,3]
[5, 2, 10, 18][ordering([5, 2, 10, 18])]
// ➔ [2,5,10,18]
MathJSON: Ordering
["Ordering", xs], ["Ordering", xs, order].
["Ordering", ["List", 5, 2, 10, 18]]
// ➔ ["List", 2, 1, 3, 4]
["At", ["List", 5, 2, 10, 18], ["Ordering", ["List", 5, 2, 10, 18]]]
// ➔ ["List", 2, 5, 10, 18]
Pair
(first: T, second: U) -> tuple<T, U> where T, U
A tuple of two elements
Pair(1, 2)
// ➔ (1, 2)
partition
(xs: indexed_collection<T>, count: ((T) any -> boolean) | integer, step: integer?) -> list<list<T>> where T: any
xs— The collection or string to split. Sample:[1, 2, 3, 4, 5].count— The number of elements of each chunk, at least 1; or a predicate that splits the elements into those that pass it and those that do not. Sample:2.step— The distance between the starts of two windows ofcountelements, at least 1; only complete windows are kept. Sample:1.
Partition a collection into consecutive chunks each of size count; the trailing chunk may be shorter when count does not divide the length.
With a third argument step, produce sliding windows of length count whose starts are step apart, keeping only complete windows.
With a predicate function instead of an integer, split into two groups: elements for which the predicate is true, and those for which it is false.
Asymmetry: with no step, the trailing partial chunk is included; with an explicit step, only complete windows are returned.
See chunk for splitting into a given number of nearly-equal groups.
partition([1, 2, 3, 4, 5], 2)
// ➔ [[1,2],[3,4],[5]]
partition([1, 2, 3, 4, 5], x => x % 2 == 0)
// ➔ [[2,4],[1,3,5]]
To split a collection into a given number of groups, use chunk.
partition([1, 2, 3, 4, 5], 2, 1)
// ➔ [[1,2],[2,3],[3,4],[4,5]]
From a string, each part (a chunk, a window or a group) is a string, so the
result is a list<string>.
[partition("abcd", 2), partition("abcde", 2, 2)]
// ➔ [["ab","cd"],["ab","cd"]]
MathJSON: Partition
["Partition", xs, size], ["Partition", xs, size, step],
["Partition", xs, predicate].
["Partition", ["List", 1, 2, 3, 4, 5], 2]
// ➔ ["List", ["List", 1, 2], ["List", 3, 4], ["List", 5]]
["Partition", ["List", 1, 2, 3, 4, 5, 6], ["IsEven", "_"]]
// ➔ ["List", ["List", 2, 4, 6], ["List", 1, 3, 5]]
pointList
(any+) -> any
- arguments 1, … — A component of the points: a collection gives one coordinate per point, a single value the same coordinate for every point. Sample:
[1, 2, 3].
A list of points: zips collection components into a List of point-tuples (Desmos point-list idiom); a plain point when no component is a collection.
pointList([1, 2, 3], [4, 5, 6])
// ➔ [(1, 4),(2, 5),(3, 6)]
MathJSON: PointList • LaTeX: \operatorname{PointList}
pointX
MathJSON PointX · (xs: collection<any> | tuple) -> any
xs— A point, or a collection of points whose x-coordinates are listed. Sample:(3, 4).
The x-coordinate of a point, broadcasting over a list of points.
pointX((3, 4))
// ➔ 3
pointX([(1, 2), (3, 4)])
// ➔ [1,3]
pointY
MathJSON PointY · (xs: collection<any> | tuple) -> any
xs— A point, or a collection of points whose y-coordinates are listed. Sample:(3, 4).
The y-coordinate of a point, broadcasting over a list of points.
pointY((3, 4))
// ➔ 4
pointZ
MathJSON PointZ · (xs: collection<any> | tuple) -> any
xs— A point of at least three coordinates, or a collection of such points whose z-coordinates are listed. Sample:(3, 4, 5).
The z-coordinate of a point, broadcasting over a list of points.
pointZ((3, 4, 5))
// ➔ 5
position
(xs: indexed_collection<T>, predicate: (T) any -> boolean) -> list<integer> where T: any
xs— The collection to search. Sample:[1, 4, 9, 16].predicate— The test applied to each element; the 1-based index of each element that passes it is in the result. Sample:x => x > 5.
Return a list of indexes of elements in the collection satisfying the predicate.
position([1, 4, 9, 16], x => x > 5)
// ➔ [3,4]
MathJSON: Position
["Position", xs, predicate].
["Position", ["List", 5, 2, 10, 18], ["Greater", "_", 5]]
// ➔ ["List", 3, 4]
positiveIntegers
constant set<integer>
The set of all positive integers.
0 in positiveIntegers
// ➔ false
MathJSON: PositiveIntegers • LaTeX: \mathbb{N}^*
positiveNumbers
constant set<real>
The set of all positive real numbers.
0 in positiveNumbers
// ➔ false
MathJSON: PositiveNumbers • LaTeX: \mathbb{R}_{>0}
primes
constant set<integer>
The set of all prime numbers.
filter(1..30, x => x in primes)
// ➔ [2,3,5,7,11,13,17,19,23,29]
MathJSON: Primes • LaTeX: \mathbb{P}
quotientRing
MathJSON QuotientRing · (set<any>, any) -> set
- argument 1 — The ring; only
Integersgives a finite collection, another ring stays inert. Sample:integers. - argument 2 — The generator of the ideal, the modulus
nforIntegers. Sample:5.
The quotient of a ring by the ideal generated by the second argument.
quotientRing(integers, n) is ℤ/nℤ, the integers modulo n.
For an integer literal n ≥ 1 it is a finite collection with n elements, and count answers. A symbolic modulus, or a base other than integers, stays inert.
The elements of ℤ/nℤ are residueClass(0, n) … residueClass(n - 1, n), which it lists, and the element type is value. Element(residueClass(k, n), ℤ/nℤ) is True. An integer is not an element: Element(7, ℤ/5ℤ) is False, because 7 is a representative of a class, not the class.
quotientRing(integers, 5)
// ➔ QuotientRing(integers, 5)
randomShuffle
((T) random -> T where T: string) & ((indexed_collection<T>) random -> list<T> where T: any)
- argument 1 — The collection or string to shuffle. Sample:
"abcd".
Randomize the order of the elements in the collection. Shuffling a string yields a string. Wrap the call in WithRandomSeed(seed, ...) to make it deterministic.
randomShuffle([1, 2, 3, 4])
There is no seed argument: wrap the call in
withRandomSeed to get the same
permutation on every evaluation.
withRandomSeed(42, randomShuffle([5, 2, 10, 18]))
// ➔ [5,18,2,10]
A permutation needs every element, so the collection is materialized. A
collection of more than 1,000,000 elements is refused with an out-of-range
error.
randomShuffle(1..2000000)
// ➔ error: Runtime error: out of range: a collection of at most 1000000 elements, 2000000
A permutation of a string is a string, built from the characters of the
source, as for reverse and take. The same holds for
randomSample.
randomShuffle("abcdef")
MathJSON: RandomShuffle
["RandomShuffle", xs]. The old name Shuffle is no longer defined.
["WithRandomSeed", 42, ["RandomShuffle", ["List", 5, 2, 10, 18]]]
// ➔ the same permutation on every evaluation
Range
(number, number?, step: number?) -> list<number>
A sequence of numbers from a start to an end value with an optional step.
1..5
// ➔ [1,2,3,4,5]
Range(1, 10, 3)
// ➔ [1,4,7,10]
a..b is Range(a, b, 1): it counts up, and it is empty when a is
greater than b, so a loop over 1..n runs zero times when n is 0. With
one argument, Range takes the argument as the upper bound and 1 as the
lower bound. With no step, the step of Range is 1, or -1 when the lower
bound is greater than the upper bound. A step of the wrong sign gives an
empty range.
Range(7)
// ➔ [1,2,3,4,5,6,7]
5..2
// ➔ []
Range(5, 2)
// ➔ [5,4,3,2]
Range(10, 1, -3)
// ➔ [10,7,4,1]
Range(5, 2, 1)
// ➔ []
Element type
The type of the elements follows the step. With no step or an integer step,
the range is a list<integer>. A step that is not an integer, or that is a
constant expression such as pi/4, gives a list<real>, and a step that is a
symbol with no value gives a list<number>.
type(Range(0, 1, 0.25))
// ➔ TypeFrom("list<real>")
type(Range(0, 1, s))
// ➔ TypeFrom("list<number>")
An exact rational bound or step gives exact elements. A float bound or step,
or a constant expression as the step, gives floats, and N of the range gives
floats.
Range(0, 1, 1/3)
// ➔ [0,1/3,2/3,1]
sum(Range(0, 1, 1/3))
// ➔ 2
Range(0, 1, pi/4)
// ➔ [0,0.7853981633974483]
N(Range(0, 1, 1/3))
// ➔ [0,0.3333333333333333,0.6666666666666666,1]
Index spans
A range whose bounds are integers, at least 1, ascending, one apart, is a
contiguous run of valid 1-based indexes: its type is the narrower range, an
index span. Every other range keeps the list types above.
[type(2..5), type(Range(7))]
// ➔ [TypeFrom("range"),TypeFrom("range")]
type(Range(1, 10, 2))
// ➔ TypeFrom("list<integer>")
type(Range(5, 2))
// ➔ TypeFrom("list<integer>")
type(Range(0, 5))
// ➔ TypeFrom("list<integer>")
A range is still an indexed_collection<integer>, so a function that
accepts a list of integers accepts it. A function that reads an index span,
such as slice, can require a range, and so reject a descending
or stepped range.
A range is an index span. It is not a mathematical interval, which is
interval, and not the statistical range
of a data set, which is max(xs) - min(xs).
Infinite ranges
The upper bound can be oo: the range is then a lazy, unbounded collection.
Its elements are integers, but its type is not range, because an index span
is a finite run of positions. length gives its extent.
type(1..oo)
// ➔ TypeFrom("list<integer>")
length(1..oo)
// ➔ +oo
take(1..oo, 3)
// ➔ [1,2,3]
MathJSON: Range • LaTeX: ..
["Range", upper], ["Range", lower, upper], ["Range", lower, upper, step].
["Range", 3, 9]
// ➔ ["List", 3, 4, 5, 6, 7, 8, 9]
["Range", 1, 10, 2]
// ➔ ["List", 1, 3, 5, 7, 9]
["Range", 0, 1, ["Rational", 1, 3]]
// ➔ ["List", 0, ["Rational", 1, 3], ["Rational", 2, 3], 1]
In LaTeX, a range is \operatorname{range}(…), the infix .., or an
ellipsis inside a list literal: [1...9] (the endpoints only),
[1, 3, ..., 9] (the step is inferred from the first two samples, here 2) or
[0, 0.1, 0.2, ..., 1] (an inferred float step). The ellipsis is ...,
\ldots or \dots. Every sample before the ellipsis must agree with the
inferred step, within ce.tolerance; [0, 0.1, 0.5, \ldots, 1] is a parse
error. Outside a list literal, an ellipsis parses as the
ContinuationPlaceholder symbol.
rangeOf
(xs: indexed_collection<T>, needle: indexed_collection<T>, from: integer?) -> missing | range where T
xs— The collection to search. Sample:[10, 20, 30, 40].needle— The run of consecutive elements to find. Sample:[30, 40].from— The 1-based index where the search starts, 1 by default. Sample:2.
Return the 1-based inclusive index span of the first occurrence of needle as a contiguous subsequence of the indexed collection, or missing when it does not occur.
The search starts at index from (1 by default) and the span is always expressed in the original collection's indices, so rangeOf(xs, needle, last(r) + 1) finds the next non-overlapping occurrence and the loop ends at missing.
On a string the needle is matched character by character, so a match never begins or ends inside a grapheme cluster.
rangeOf([10, 20, 30, 40], [30, 40])
// ➔ [3,4]
The span is a 1-based inclusive range of indexes. Printed by itself, it shows
each of its indexes; inside a list, it shows as a Range.
rangeOf([9, 7, 5, 3], [7, 5])
// ➔ [2,3]
[rangeOf("hello world", "o w"), rangeOf("hello", "e")]
// ➔ [Range(5, 7),Range(2, 2)]
rangeOf([9, 7, 5, 3], [7, 3])
// ➔ missing
rangeOf and its three companions containsSequence,
startsWith and endsWith read their second
argument as a sequence of elements. This is what separates them from
contains and indexOf:
| Question | Function |
|---|---|
Is v one of the elements? | contains(xs, v) |
At what index is the element v? | indexOf(xs, v) |
| Do these elements occur consecutively? | containsSequence(xs, needle) |
| At what indexes? | rangeOf(xs, needle) |
With nested lists, one function for both questions could not tell
indexOf([[1, 2], [3, 4]], [3, 4]), the element equal to [3, 4], from the
subsequence 3 then 4.
Searching from an index
The optional third argument is the index where the search starts, 1 by
default. The span is always in the indexes of the whole collection, so the
next match that does not overlap starts at last(r) + 1 (or first(r) + 1
to allow overlaps), and a loop that runs until Missing finds all of them.
let xs = [1, 2, 1, 2, 1]
let r = rangeOf(xs, [1, 2])
rangeOf(xs, [1, 2], last(r) + 1)
// ➔ [3,4]
| Case | Result |
|---|---|
| The needle does not occur | Missing |
| The start index is past the end | Missing, never an error: a match at the very end can produce length(xs) + 1 |
| The start index is less than 1, or not an integer | An error |
| The needle is empty | An error: an empty span cannot be written (1..0 is the descending range from 1 to 0) |
| The collection or the needle is infinite, or of unknown length | Unevaluated: the search would not end when the needle does not occur |
rangeOf([9, 7, 5, 3], [3], 5)
// ➔ missing
rangeOf([9, 7, 5, 3], [7], 0)
// ➔ error: Runtime error: out of range: an index of 1 or more, 0
rangeOf([9, 7, 5, 3], [])
// ➔ error: Runtime error: out of range: a non-empty needle, []
rangeOf(1..oo, [7, 5])
// ➔ RangeOf(1..oo, [7,5])
With slice
When the needle is found, slice(xs, rangeOf(xs, needle)) has the elements
of the needle. slice gives Missing for the Missing of a
failed search, so the two compose without a test in between. Test the result
with isMissing or replace it with
Coalesce.
slice([9, 7, 5, 3], rangeOf([9, 7, 5, 3], [7, 5]))
// ➔ [7,5]
slice([9, 7, 5, 3], rangeOf([9, 7, 5, 3], [1]))
// ➔ missing
On a string the elements are characters, so the search is character by character and the span is in character indexes. The strings reference describes how this case treats grapheme clusters.
rangeOf("hello", "ll")
// ➔ [3,4]
On a string, the comparison is between whole characters, so a needle never matches across the boundary of a grapheme cluster (see Searching for a substring). The span prints as the list of its indexes.
rangeOf("hello world", "o w")
// ➔ [5,6,7]
slice("hello world", rangeOf("hello world", "o w"))
// ➔ "o w"
rangeOf("abcabc", "bc", 4)
// ➔ [5,6]
rangeOf("abcabc", "bc", 6)
// ➔ missing
The needle can be a collection of another kind than the subject: a string searched with a list of characters gives a span in the character indexes of the string.
rangeOf("abc", characters("bc"))
// ➔ [2,3]
slice("abc", rangeOf("abc", characters("bc")))
// ➔ "bc"
When the needle is found, slice(xs, rangeOf(xs, needle)) has the elements
of the needle, in order. It is not == needle in every case: slice keeps
the kind of xs, so with a string subject and a list of characters as the
needle, one side is a string and the other a list, which are never equal.
When the needle and the subject are of the same kind, they are equal.
MathJSON: RangeOf
["RangeOf", xs, needle], ["RangeOf", xs, needle, from]. The span is a
Range.
["RangeOf", ["List", 9, 7, 5, 3], ["List", 7, 5]]
// ➔ ["Range", 2, 3]
["Slice", ["List", 9, 7, 5, 3], ["RangeOf", ["List", 9, 7, 5, 3], ["List", 7, 5]]]
// ➔ ["List", 7, 5]
["RangeOf", {str: "hello world"}, {str: "o w"}]
// ➔ ["Range", 5, 7]
["RangeOf", {str: "abc"}, {str: "z"}]
// ➔ "Missing"
rationalNumbers
constant set<rational>
The set of all finite rational numbers.
sqrt(2) in rationalNumbers
// ➔ false
MathJSON: RationalNumbers • LaTeX: \mathbb{Q}
realNumbers
constant set<real>
The set of all finite real numbers.
i in realNumbers
// ➔ false
MathJSON: RealNumbers • LaTeX: \mathbb{R}
reduce
(xs: collection<T>, reducer: (unknown, T) any -> unknown, initial: value?) -> value where T
xs— The collection to fold; an empty one givesinitial, orNothingwithout it. Sample:[1, 2, 3, 4].reducer— The function of the accumulated value and the next element that gives the new accumulated value. Sample:(a, b) => a * b.initial— The accumulated value before the first element; without it, the first element. Sample:1.
Reduce (fold) a collection to a single value by repeatedly applying a binary function, with an optional initial value.
reduce([1, 2, 3, 4], (a, b) => a * b)
// ➔ 24
reduce is a left fold: the function is applied to the first two elements,
then to that result and the next element, and so on. With an initial value,
the first step applies it to the initial value and the first element.
The initial value is evaluated once, at the first step or when the
collection is empty, and the function receives its value, not the expression
as written. Without an initial value, an empty collection gives Nothing.
reduce([1, 2, 3], (a, b) => a - b, 10)
// ➔ 4
reduce([], (a, b) => a + b, 1 + 4 % 3)
// ➔ 2
reduce([], (a, b) => a + b) == Nothing
// ➔ true
The name of a function of two arguments can stand for the function.
reduce([5, 2, 10, 18], max)
// ➔ 18
fold is the same fold with the function first. See also
fixedPoint, which iterates
without a collection.
MathJSON: Reduce
["Reduce", xs, f], ["Reduce", xs, f, initial]. The name of an operator,
such as "Add", stands for the function of two arguments.
["Reduce", ["List", 5, 2, 10, 18], "Add"]
// ➔ 35
["Reduce", ["List", 5, 2, 10, 18], ["Function", ["Add", "_1", "_2"]]]
// ➔ 35
["Reduce", ["List"], "Add", ["Add", 1, ["Mod", 4, 3]]]
// ➔ 2
repeat
(value: any, count: integer?) -> list
value— The value to repeat; a value that is not pure is evaluated again for each element. Sample:0.count— The number of copies, 0 or less for an empty list; without it the sequence is infinite. Sample:3.
Produce a sequence by repeating a single value. With 1 argument, returns an infinite sequence; with 2 arguments (value, count), returns a finite list of count copies. A value that is not pure (random()) is evaluated once per element, in order, and each read of an element of a lazy repeat evaluates it again.
repeat(0, 3)
// ➔ [0,0,0]
The result has the type list<T>, where T is the type of the value.
For a pure x, repeat(x) is cycle([x]); see cycle.
A value that is not pure, such as random(), is evaluated once per element,
in order: repeat(random(), 3) is three different numbers. A pure value is
evaluated once.
type(repeat(False, 3))
// ➔ TypeFrom("list<boolean>")
repeat(1)
// ➔ [1,1,1,1,1,...]
take(repeat(7), 3) == take(cycle([7]), 3)
// ➔ true
MathJSON: Repeat
["Repeat", value], ["Repeat", value, count].
["Repeat", 42, 5]
// ➔ ["List", 42, 42, 42, 42, 42]
replaceAt
((xs: indexed_collection<T>, index: integer, element: T) -> list<T> where T: any) & ((xs: indexed_collection<any>, index: integer, integer, any+) -> list<any>)
xs— The collection; a string gives a list of its characters. Sample:[1, 2, 3].index— The 1-based position of the element to replace; a negative index counts from the end. With more positions, the position in the outermost level. Sample:2.element— The new element. Sample:20.
Return a copy of the indexed collection with the element at the 1-based index replaced by element.
A negative index counts from the end. An out-of-range, zero, or non-integer index leaves the expression unevaluated.
With more than one position, as At takes them, the last operand is the value, and each position selects one level of a nested collection (e.g., a matrix).
replaceAt([1, 2, 3], 2, 20)
// ➔ [1,20,3]
replaceAt([[1, 2], [3, 4]], 2, 1, 9)
// ➔ [[1,2],[9,4]]
The collection is not changed. An index out of range, or a symbol, at any level, leaves the call unevaluated. More positions than the collection has levels is an error.
replaceAt([[1, 2], [3, 4]], -1, -1, 9)
// ➔ [[1,2],[3,9]]
replaceAt([[1, 2], [3, 4]], 5, 1, 9)
// ➔ ReplaceAt([[1,2],[3,4]], 5, 1, 9)
replaceAt([1, 2, 3], 1, 1, 9)
// ➔ error: Runtime error: expected `indexed_collection<integer>`, got `1` at `1`
A replacement does not change the length of a list. When the value fits the
element type, the result has the type of the collection, so a vector<3>
stays a vector<3>. Otherwise the element type widens to include the value,
and the result type has no length.
type(replaceAt([1, 2, 3], 2, 9))
// ➔ TypeFrom("vector<integer^3>")
type(replaceAt([1, 2, 3], 2, "a"))
// ➔ TypeFrom("list<integer | string>")
The form with more than one position compiles to JavaScript only, and only
when the type of the collection shows a list at each level it writes: a
list<list<number>> or a matrix compiles, and a list<any>, or a list
that can hold a string or Missing as a row, does not. See
Compiling expressions.
MathJSON: ReplaceAt
["ReplaceAt", xs, index, value], ["ReplaceAt", xs, i, j, …, value].
["ReplaceAt", ["List", 1, 2, 3], 2, 99]
// ➔ ["List", 1, 99, 3]
["ReplaceAt", ["List", ["List", 1, 2], ["List", 3, 4]], 2, 1, 9]
// ➔ ["List", ["List", 1, 2], ["List", 9, 4]]
residueClass
(k: any, n: any) -> residue
k— The representative of the class, an exact integer or a rational whose denominator is a unit modn. Sample:7.n— The modulus, an exact integer literal ≥ 1. Sample:5.
An element of ℤ/nℤ: the class of the integer k modulo n.
The canonical form reduces k into 0…n−1, so residueClass(7, 5) is residueClass(2, 5), and two classes are equal when their canonical forms are. n must be an exact integer literal ≥ 1, and k an exact integer (or a rational with a denominator that is a unit mod n); any other call stays inert, a float k or n included.
Sums, differences, products and integer powers of classes of one modulus are classes. An exact integer or rational next to a class is read in its ring: residueClass(5, 7) + 3 is residueClass(1, 7). A float is not. Arithmetic on classes of different moduli stays unevaluated. The inverse, a division and a negative power need a unit: when gcd(k, n) ≠ 1 they stay unevaluated.
Classes are not ordered, and Mod is not this: Mod(7, 5) is the integer remainder 2. The elements of quotientRing(integers, n) are the classes residueClass(0, n) … residueClass(n - 1, n).
LaTeX: \overline{k}_{n}, for integer literals k and n ≥ 1.
residueClass(7, 5)
// ➔ ResidueClass(2, 5)
residueClass(5, 7) + residueClass(4, 7)
// ➔ ResidueClass(2, 7)
1 / residueClass(3, 7)
// ➔ ResidueClass(5, 7)
The canonical form reduces k into [0, n). A rational k whose
denominator is coprime to n is read as u · v⁻¹ in the ring. A float, a
symbolic k or n, or a modulus less than 1 stays inert.
[residueClass(7, 5), residueClass(-1, 7)]
// ➔ [ResidueClass(2, 5),ResidueClass(6, 7)]
residueClass(1/3, 7)
// ➔ ResidueClass(5, 7)
[residueClass(2.5, 5), residueClass(x, 5)]
// ➔ [ResidueClass(2.5, 5),ResidueClass(x, 5)]
Two classes with the same modulus and the same reduced k are equal.
Classes are not ordered.
residueClass(7, 5) == residueClass(2, 5)
// ➔ true
residueClass(1, 3) < residueClass(2, 3)
// ➔ ResidueClass(1, 3) < ResidueClass(2, 3)
Arithmetic
Sums, differences, products and integer powers of classes with one modulus
are classes. An exact integer, or a rational whose denominator is coprime to
the modulus, is read in the ring. An inverse, a quotient or a negative power
needs gcd(k, n) = 1; otherwise the expression stays symbolic.
residueClass(5, 7) + residueClass(4, 7)
// ➔ ResidueClass(2, 7)
residueClass(5, 7) + 3
// ➔ ResidueClass(1, 7)
residueClass(3, 7)^100
// ➔ ResidueClass(4, 7)
1 / residueClass(3, 7)
// ➔ ResidueClass(5, 7)
1 / residueClass(2, 4)
// ➔ 1 / ResidueClass(2, 4)
A class of another modulus, a float or an infinity is never combined with a
class: the expression stays symbolic. The rules of the numbers do not apply
to a class: c / c is not cancelled to 1 when c has no inverse.
residueClass(1, 5) + residueClass(1, 7)
// ➔ ResidueClass(1, 5) + ResidueClass(1, 7)
residueClass(3, 7) * 1.5
// ➔ 1.5 * ResidueClass(3, 7)
let c = residueClass(2, 4)
c / c
// ➔ ResidueClass(2, 4) / ResidueClass(2, 4)
solve, D and integrate stay symbolic for an expression that holds a
class.
D(residueClass(3, 7) * x, x)
// ➔ D(x * ResidueClass(3, 7), x)
The ring itself, quotientRing(Integers, n), is the finite collection of
its n classes; see
quotientRing. a % n is the
integer remainder, not a class: 7 % 3 is 1.
[k for k in quotientRing(Integers, 3)]
// ➔ [ResidueClass(0, 3),ResidueClass(1, 3),ResidueClass(2, 3)]
MathJSON: ResidueClass
["ResidueClass", k, n]. In LaTeX, a class is written \overline{k}_{n}
with integer literals k and n, and it serializes back the same way. A
bare \overline{7} is ["Conjugate", 7], and \overline{z}_1 is
["Subscript", ["Conjugate", "z"], 1]. The ring is written
\mathbb{Z}/n\mathbb{Z} or \mathbb{Z}_n.
["ResidueClass", 7, 5]
// ➔ ["ResidueClass", 2, 5]
["ResidueClass", -1, 7]
// ➔ ["ResidueClass", 6, 7]
["ResidueClass", ["Rational", 1, 3], 7]
// ➔ ["ResidueClass", 5, 7]
["Equal", ["ResidueClass", 7, 5], ["ResidueClass", 2, 5]]
// ➔ "True"
["Add", ["ResidueClass", 5, 7], ["ResidueClass", 4, 7]]
// ➔ ["ResidueClass", 2, 7]
["Divide", 1, ["ResidueClass", 2, 4]]
// ➔ ["Divide", 1, ["ResidueClass", 2, 4]]
["Mod", 7, 3]
// ➔ 1
rest
((T) -> T where T: string) & ((indexed_collection<T>) -> list<T> where T: any)
- argument 1 — The collection or string; an empty one gives an empty result. Sample:
"abc".
Return the collection without the first element.
If the collection has only one element, return an empty collection.
rest([7, 8, 9])
// ➔ [8,9]
rest(xs) is drop(xs, 1). Of a string, it is a string.
rest("hello")
// ➔ "ello"
take(rest(1..oo), 3)
// ➔ [2,3,4]
MathJSON: Rest
["Rest", xs].
["Rest", ["List", 5, 2, 10, 18]]
// ➔ ["List", 2, 10, 18]
reverse
((T) -> T where T: string) & ((T) -> T where T: list) & ((indexed_collection<T>) -> list<T> where T: any)
- argument 1 — The collection to reverse; a string gives the string of its characters in reverse order. Sample:
[1, 2, 3].
Reverse the order of the elements of an indexed collection.
reverse([1, 2, 3])
// ➔ [3,2,1]
A list keeps its type, its shape included: a vector<3> reversed is a
vector<3>. A string gives a string. Any other indexed collection, such as a
tuple or a range, gives a list of the same elements: a reversed tuple would
have its element types in the wrong order, and a reversed range is
descending, which the range type excludes.
[reverse("abc"), reverse((1, "a", 2)), reverse(1..4)]
// ➔ ["cba",[2,"a",1],[4,3,2,1]]
type(reverse([1, 2, 3]))
// ➔ TypeFrom("vector<integer^3>")
reverse is lazy: the reversed collection is not built until its elements
are read.
MathJSON: Reverse
["Reverse", xs].
["Reverse", ["List", 5, 2, 10, 18]]
// ➔ ["List", 18, 10, 2, 5]
rotateLeft
((xs: T, n: integer?) -> T where T: string) & ((xs: T, n: integer?) -> T where T: list) & ((xs: indexed_collection<T>, n: integer?) -> list<T> where T: any)
xs— The collection to rotate; a string gives a string. Sample:[1, 2, 3, 4].n— The number of positions, 1 by default; a negativenrotates to the right, andnis taken modulo the length. Sample:2.
Rotate the elements of the collection to the left by n positions.
rotateLeft([1, 2, 3, 4])
// ➔ [2,3,4,1]
The second argument is the number of positions, 1 by default. A string gives a string.
[rotateLeft([5, 2, 10, 18], 2), rotateLeft("abcd", 1)]
// ➔ [[10,18,5,2],"bcda"]
MathJSON: RotateLeft
["RotateLeft", xs], ["RotateLeft", xs, count].
["RotateLeft", ["List", 5, 2, 10, 18], 2]
// ➔ ["List", 10, 18, 5, 2]
rotateRight
((xs: T, n: integer?) -> T where T: string) & ((xs: T, n: integer?) -> T where T: list) & ((xs: indexed_collection<T>, n: integer?) -> list<T> where T: any)
xs— The collection to rotate; a string gives a string. Sample:[1, 2, 3, 4].n— The number of positions, 1 by default; a negativenrotates to the left, andnis taken modulo the length. Sample:2.
Rotate the elements of the collection to the right by n positions.
rotateRight([1, 2, 3, 4])
// ➔ [4,1,2,3]
The second argument is the number of positions, 1 by default. A string gives a string.
rotateRight([5, 2, 10, 18], 1)
// ➔ [18,5,2,10]
MathJSON: RotateRight
["RotateRight", xs], ["RotateRight", xs, count].
["RotateRight", ["List", 5, 2, 10, 18], 1]
// ➔ ["List", 18, 5, 2, 10]
scan
(xs: indexed_collection<T>, reducer: (unknown, T) any -> unknown, initial: value?) -> indexed_collection where T
xs— The collection to scan, in its order; an empty collection gives an empty result. Sample:[1, 2, 3, 4].reducer— A function of the running result and the next element that returns the new running result. Sample:(acc, x) => acc + x.initial— The value the running result starts from; without it, the first element of the result is the first element of the collection. Sample:0.
Return the cumulative fold of a collection: a same-length collection whose k-th element is the running result of applying a binary function left to right (optionally seeded by an initial value).
scan([1, 2, 3, 4], (a, b) => a + b)
// ➔ [1,3,6,10]
Unlike reduce, which returns only the final value, scan
returns every intermediate value: its n-th element is the fold of the
first n elements. With an initial value, the first element is
f(initial, x1).
scan([3, 1, 4, 1, 5], max)
// ➔ [3,3,4,4,5]
scan([1, 2, 3, 4], (a, b) => a + b, 100)
// ➔ [101,103,106,110]
scan is lazy: the elements are computed when they are read.
MathJSON: Scan
["Scan", xs, f], ["Scan", xs, f, initial].
["Scan", ["List", 1, 2, 3, 4], "Add"]
// ➔ ["List", 1, 3, 6, 10]
second
(xs: indexed_collection<any>) -> any
xs— The collection; one with fewer than two elements givesMissing, orNaNwhen its elements are numbers. Sample:[7, 8, 9].
The second element of a collection.
second([7, 8, 9])
// ➔ 8
second(xs) is xs[2].
second((x, y))
// ➔ y
MathJSON: Second
["Second", xs].
["Second", ["Tuple", "x", "y"]]
// ➔ "y"
set
(any*) -> set
An unordered collection of distinct elements (a set).
set(3, 1, 2, 1)
// ➔ Set(1, 2, 3)
A set is a non-indexed collection of distinct elements. The type of a set
is set<T>; set is short for set<any>. A repeated element is kept once:
two elements are the same when IsSame says they are.
set(12, 15, 17, 12, 15)
// ➔ Set(12, 15, 17)
The elements of a set have no order. An enumeration returns them in an arbitrary order, and two enumerations may return them in different orders. The elements of a set are counted in constant time.
...xs in a set literal splices the elements of xs, with the same rules as
in a list literal: a string spreads into its characters, and a tuple
does not spread.
set(...set(1, 2), 3)
// ➔ Set(1, 2, 3)
MathJSON: Set • LaTeX: {, }
["Set", ...elements].
["Set", 12, 15, 17, 12, 15]
// ➔ ["Set", 12, 15, 17]
["Set", 1, ["Spread", ["List", 2, 2, 3]]]
// ➔ ["Set", 1, 2, 3]
In LaTeX, \lbrace 12, 15, 17 \rbrace.
setFrom
(value*) -> set
- arguments 1, … — A collection whose elements go into the set, or a value that is not a collection, which goes into the set as an element. Sample:
[1, 2, 2, 3].
Create a set from the elements of a collection.
setFrom([1, 2, 2, 3])
// ➔ Set(1, 2, 3)
The collection must be finite. An element that occurs more than once is kept once.
setFrom(1..3)
// ➔ Set(1, 2, 3)
MathJSON: SetFrom
["SetFrom", xs].
["SetFrom", ["Range", 1, 3]]
// ➔ ["Set", 1, 2, 3]
setMinus
(set<any>, value*) -> set
- argument 1 — The set to remove elements from. Sample:
Set(1, 2, 3, 4). - arguments 2, … — A value to remove, or a collection whose elements are removed; a string is removed as one value. Sample:
2.
Return the set difference between the first set and subsequent values.
setMinus(set(1, 2, 3, 4), 2, 4)
// ➔ Set(1, 3)
MathJSON: SetMinus • LaTeX: \setminus
Single
(value: T) -> tuple<T> where T
A tuple with a single element
Single(5)
// ➔ (5)
slice
((value: T, span: range) -> T where T: string) & ((value: T, start: number, end: number) -> T where T: string) & ((value: indexed_collection<T>, span: range) -> list<T> where T: any) & ((value: indexed_collection<T>, start: number, end: number) -> list<T> where T: any)
value— The collection to slice; a string gives a string. Sample:[10, 20, 30, 40, 50].span— An ascending range of 1-based indices; the indices past the end are left out. Sample:2..4.start— The 1-based index of the first element; a negative index counts from the end (-1is the last element), and 0 or an index before the first element is the first element. Sample:2.end— The 1-based index of the last element, included; a negative index counts from the end, an index past the end is the end, and anendbeforestart(0 included) gives an empty result. Sample:4.
Return a contiguous run of elements from an indexed collection.
Given start and end (1-based, inclusive), a negative index is counted from the end. The result is the part of start to end that is in the collection: a start of 0 or before the first element is the first element, and an end of 0 or before the first element gives an empty result.
Given a range (an ascending index span such as 2..4), returns the elements at those indices: slice(xs, r) is slice(xs, first(r), last(r)).
slice([10, 20, 30, 40, 50], 2, 4)
// ➔ [20,30,40]
slice is lazy. A start past the end, or after end, gives an empty
result. Of a string, the result is a string.
slice([5, 2, 10, 18], -3, -1)
// ➔ [2,10,18]
slice([5, 2, 10, 18], 5, 9)
// ➔ []
slice("hello", 2, 4)
// ➔ "ell"
With a range
slice(xs, r) is slice(xs, first(r), last(r)), with the same clamping. The
range must be a range: an ascending, finite span of 1-based
indexes with step 1. A descending or stepped range is not a range, and the
expression stays unevaluated: read as bounds it would contradict its own
elements, since slice(xs, 3, 2) is empty while Range(3, 2) is [3, 2]. To
gather elements at any indexes, in any order, index with a list of indexes
(see At).
slice([5, 2, 10, 18], 3..9)
// ➔ [10,18]
let xs = [5, 2, 10, 18]; slice(xs, Range(3, 2))
// ➔ Slice([5,2,10,18], Range(3, 2))
An absent span gives Missing, as every function of Missing does. A span
from rangeOf, which is Missing when
the needle is absent, can therefore be sliced with no test in between:
slice([9, 7, 5, 3], rangeOf([9, 7, 5, 3], [7, 5]))
// ➔ [7,5]
slice([9, 7, 5, 3], rangeOf([9, 7, 5, 3], [1, 2]))
// ➔ missing
MathJSON: Slice
["Slice", xs, start, end], ["Slice", xs, span].
["Slice", ["List", 5, 2, 10, 18], 2, 3]
// ➔ ["List", 2, 10]
["Slice", ["List", 5, 2, 10, 18], ["Range", 2, 3]]
// ➔ ["List", 2, 10]
sort
((T, order: (((character) any -> unknown) | ((character, character) any -> boolean | number))?) -> T where T: string) & ((indexed_collection<T>, order: (((T) any -> unknown) | ((any, any) any -> boolean | number))?) -> list<T> where T: any)
- argument 1 — The collection to sort; a string gives the string of its characters in order. Sample:
[3, 1, 2]. order— A key function of one element, whose values are sorted in ascending order, or a comparison of two elements that returnsTrueor a negative number when the first goes first; by default, ascending order. Sample:x => -x.
Return the elements of the collection sorted according to the given comparison function.
sort([3, 1, 2])
// ➔ [1,2,3]
sort(["pear", "fig", "apple"], length)
// ➔ ["fig","pear","apple"]
The collection must be indexed: a set has no positions to permute, and
sorting one is an incompatible-type error. A string sorts its characters
and gives a string.
sort("dcba")
// ➔ "abcd"
sort(set(3, 1, 2))
// ➔ error: Type error: expected `indexed_collection`, got `set<integer>` at `set(1, 2, 3)` in `sort(set(3, 1, 2))`
The order function
The optional function is read by its number of parameters.
A comparator of two parameters, (a, b) => …, returns a negative number
when a comes before b, zero when they are equivalent, and a positive
number otherwise. It can also return a boolean: True means that a comes
first, which is what a body such as a > b gives.
sort([3, 1, 2], (a, b) => b - a)
// ➔ [3,2,1]
sort([1, 2, 3], (a, b) => a > b)
// ➔ [3,2,1]
A key function of one parameter sorts the elements in ascending order of their key. The sort is stable: elements with equal keys keep their order.
sort([-3, 1, -2, 3, 2], abs)
// ➔ [1,-2,2,-3,3]
MathJSON: Sort
["Sort", xs], ["Sort", xs, order].
["Sort", ["List", 18, 5, 2, 10]]
// ➔ ["List", 2, 5, 10, 18]
["Sort", ["List", 3, 1, 2], ["Function", ["Subtract", "b", "a"], "a", "b"]]
// ➔ ["List", 3, 2, 1]
["Sort", ["List", -3, 1, -2], ["Abs", "_"]]
// ➔ ["List", 1, -2, -3]
startsWith
(xs: indexed_collection<T>, prefix: indexed_collection<T>) -> boolean where T
xs— The collection or string whose start is tested. Sample:[1, 2, 3].prefix— The elements the collection must begin with, in order; an empty prefix matches every collection. Sample:[1, 2].
Return True when the indexed collection begins with prefix as a contiguous subsequence.
On a string the prefix is matched character by character, so a prefix that would end inside a grapheme cluster does not match. An empty prefix matches everything.
startsWith([1, 2, 3], [1, 2])
// ➔ true
An empty prefix is True. Over an infinite collection, startsWith stays
unevaluated.
startsWith("hello", "he")
// ➔ true
startsWith(1..oo, [1, 2])
// ➔ StartsWith(1..oo, [1,2])
A prefix that would end inside a grapheme cluster does not match: the first
and only character of "👨👩👧" is the whole family, not 👨.
startsWith("👨👩👧", "👨")
// ➔ false
startsWith("hello", "")
// ➔ true
MathJSON: StartsWith
["StartsWith", xs, prefix].
["StartsWith", ["List", 1, 2, 3], ["List", 1, 2]]
// ➔ "True"
["StartsWith", {str: "hello"}, {str: "he"}]
// ➔ "True"
subset
(any, any*) -> boolean
- argument 1 — The collection tested as a strict subset. Sample:
Set(1, 2). - arguments 2, … — A collection that strictly contains the collection before it; with more than two arguments, each argument is tested against the next. Sample:
Set(1, 2, 3).
Test whether the first collection is a strict subset of the second.
subset(set(1, 2), set(1, 2, 3))
// ➔ true
MathJSON: Subset • LaTeX: \subset
subsetEqual
(any, any*) -> boolean
- argument 1 — The collection tested as a subset. Sample:
Set(1, 2). - arguments 2, … — A collection that contains the collection before it; with more than two arguments, each argument is tested against the next. Sample:
Set(1, 2, 3).
Test whether the first collection is a subset (possibly equal) of the second.
subsetEqual(set(1, 2, 3), set(1, 2, 3))
// ➔ true
MathJSON: SubsetEqual • LaTeX: \subseteq
superset
(any, any*) -> boolean
- argument 1 — The collection tested as a strict superset. Sample:
Set(1, 2, 3). - arguments 2, … — A collection that the collection before it strictly contains; with more than two arguments, each argument is tested against the next. Sample:
Set(1, 2).
Test whether the first collection is a strict superset of the second.
superset(set(1, 2, 3), set(1, 2))
// ➔ true
MathJSON: Superset • LaTeX: \supset
supersetEqual
(any, any*) -> boolean
- argument 1 — The collection tested as a superset. Sample:
Set(1, 2, 3). - arguments 2, … — A collection that the collection before it contains; with more than two arguments, each argument is tested against the next. Sample:
Set(1, 2).
Test whether the first collection is a superset (possibly equal) of the second.
supersetEqual(set(1, 2), set(1, 2))
// ➔ true
MathJSON: SupersetEqual • LaTeX: \supseteq
swap
MathJSON Swap · (array, array) state -> nothing
- argument 1 — The first array. Sample:
arrayFrom([1, 2]). - argument 2 — The second array, of the same cell type. Sample:
arrayFrom([3, 4, 5]).
Exchange the cells and the counts of two arrays of one cell type, in constant time, with no cell copied.
Neither array changes identity: every name, field and tuple that holds an array still holds it, with the cells of the other. The value is nothing.
swap(arrayFrom([1, 2]), arrayFrom([3, 4, 5]))
symmetricDifference
(set<any>, set<any>) -> set
- argument 1 — The first set. Sample:
Set(1, 2, 3). - argument 2 — The second set; the order of the two sets does not change the result. Sample:
Set(2, 3, 4).
Return the symmetric difference of two sets (elements in either set but not both).
symmetricDifference(set(1, 2, 3), set(2, 3, 4))
// ➔ Set(1, 4)
MathJSON: SymmetricDifference • LaTeX: \triangle
table
(function, integer+) -> collection
- argument 1 — The function of the indices, or an expression in the index variables of the iterator specs. Sample:
i => i^2. - arguments 2, … — The size of one dimension, or an iterator:
i in xs,(i, n),(i, lo, hi)or(i, lo, hi, step). Sample:5.
Return the list of the values of a function at each index of the given dimensions, as tabulate (the preferred name) does.
It also takes iterators: an index over a collection, table(i^2, i in 1..n), or an iterator tuple, table(i^2, (i, n)) (i from 1 to n), table(i^2, (i, 1, n)) or table(i, (i, lo, hi, step)). Several iterators give a nested list, the first iterator outermost.
table(i^2, i in 1..5)
// ➔ [1,4,9,16,25]
table(i * j, i in 1..2, j in 1..3)
// ➔ [[1,2,3],[2,4,6]]
Each iterator spec names an index and its bounds, and the body is evaluated
once for each value of the index. A spec is written with parentheses:
(k, 1, 5). A fourth element is a step.
table(k^2, (k, 1, 5))
// ➔ [1,4,9,16,25]
table(k, (k, 1, 10, 4))
// ➔ [1,5,9]
Several specs iterate as nested loops, the first spec outermost, and give a nested list:
table(i * j, (i, 1, 2), (j, 1, 3))
// ➔ [[1,2,3],[2,4,6]]
With a function and no iterator spec, table is
tabulate:
table(i => i^2, 5)
// ➔ [1,4,9,16,25]
The other functions that take a spec read it the same way, step included.
integrate has no step: a spec of four elements is an error.
sum(k, (k, 1, 10, 2))
// ➔ 25
integrate(x, (x, 0, 1, 2))
// ➔ error: Type error: incompatible type: tuple<symbol, any, any> at `(x, 0, 1, 2)` in `integrate(x, (x, 0, 1, 2))`
MathJSON: Table
["Table", f, d1, d2, ...], ["Table", body, spec1, ...specs]. A spec is a
Tuple or a Set: ["Tuple", "k", 1, 5] or ["Set", "k", 1, 5].
["Table", ["Square", "k"], ["Tuple", "k", 1, 5]]
// ➔ ["List", 1, 4, 9, 16, 25]
["Table", ["Multiply", "i", "j"], ["Tuple", "i", 1, 2], ["Tuple", "j", 1, 3]]
// ➔ ["List", ["List", 1, 2, 3], ["List", 2, 4, 6]]
tabulate
(generator: function, integer+) -> list
generator— The function, called with one 1-based index for each dimension. Sample:i => i^2.- arguments 2, … — The size of one dimension, one argument for each dimension; a size less than 1 gives no element in that dimension. Sample:
3.
Create a collection by applying a function to each index in the specified dimensions.
tabulate((i, j) => i * j, 2, 3)
// ➔ [[1,2,3],[2,4,6]]
Indexes start at 1. The function receives one index for each dimension, and with several dimensions the result is a nested list. Any number of dimensions is accepted, and a dimension of 0 gives an empty list.
tabulate(i => i^2, 5)
// ➔ [1,4,9,16,25]
tabulate(Add, 2, 2, 3)
// ➔ [[[3,4,5],[4,5,6]],[[4,5,6],[5,6,7]]]
tabulate((i, j) => i + j, 2, 0)
// ➔ [[],[]]
To give every element the same value, use
fill.
MathJSON: Tabulate
["Tabulate", f, d1, d2, ...].
["Tabulate", ["Function", ["Square", "i"], "i"], 5]
// ➔ ["List", 1, 4, 9, 16, 25]
["Tabulate", ["Function", ["Add", "i", "j"], "i", "j"], 2, 3]
// ➔ ["List", ["List", 2, 3, 4], ["List", 3, 4, 5]]
take
((xs: T, count: number) -> T where T: string) & ((xs: indexed_collection<T>, count: number) -> list<T> where T: any)
Return the first n elements of an indexed collection.
A negative n counts from the end: take(xs, -n) is the last n elements.
A count past the length is clamped: the result is the whole collection.
take([1, 2, 3, 4, 5], 2)
// ➔ [1,2]
take([1, 2, 3, 4, 5], -2)
// ➔ [4,5]
take is lazy. A count of 0 gives the empty collection, and a count past the
length, in either direction, gives the whole collection. Of a string, the
result is a string.
take([5, 2, 10, 18], -10)
// ➔ [5,2,10,18]
take("hello", -2)
// ➔ "lo"
A negative count needs the length of the collection. When the length is not known or is infinite, the expression stays unevaluated.
take(1..oo, -2)
// ➔ Take(1..oo, -2)
See drop for the elements after the first n.
MathJSON: Take
["Take", xs, n].
["Take", ["List", 5, 2, 10, 18], -2]
// ➔ ["List", 10, 18]
["Take", "'hello'", -2]
// ➔ "'lo'"
takeWhile
(xs: indexed_collection<T>, predicate: (T) any -> boolean) -> indexed_collection where T
xs— The collection whose leading elements are taken; a string gives a string. Sample:[1, 2, 3, 10, 4].predicate— A function of one element that returnsTruefor an element to keep. Sample:x => x < 5.
Return the leading elements of the collection for which the predicate returns True, stopping at the first element that does not.
takeWhile([1, 2, 3, 10, 4], x => x < 5)
// ➔ [1,2,3]
takeWhile is lazy and stops at the first element that fails the predicate,
which is not included. It therefore works on an infinite collection.
takeWhile(1..oo, x => x < 4)
// ➔ [1,2,3]
See dropWhile for the elements that remain.
MathJSON: TakeWhile
["TakeWhile", xs, predicate].
["TakeWhile", ["List", 1, 2, 3, 10, 1], ["Function", ["Less", "x", 5], "x"]]
// ➔ ["List", 1, 2, 3]
tally
(collection<T>) -> tuple<list<T>, list<integer>> where T
- argument 1 — The collection whose elements are counted; equal elements are counted together. Sample:
["a", "b", "a"].
Return a tuple with the unique elements of the collection and their respective counts.
tally(["a", "b", "a", "c", "a"])
// ➔ (["a","b","c"], [3,1,1])
The first list holds each distinct element once, in the order of its first occurrence; the second list holds the number of occurrences of each.
tally([5, 2, 10, 18, 5, 2, 5])
// ➔ ([5,2,10,18], [3,2,1,1])
MathJSON: Tally
["Tally", xs].
["Tally", ["List", 5, 2, 10, 18, 5, 2, 5]]
// ➔ ["Tuple", ["List", 5, 2, 10, 18], ["List", 3, 2, 1, 1]]
third
(xs: indexed_collection<any>) -> any
xs— The collection; one with fewer than three elements givesMissing, orNaNwhen its elements are numbers. Sample:[7, 8, 9].
The third element of a collection.
third([7, 8, 9])
// ➔ 9
third(xs) is xs[3].
MathJSON: Third
["Third", xs].
["Third", ["List", 5, 2, 10, 18]]
// ➔ 10
Triple
(first: T, second: U, third: V) -> tuple<T, U, V> where T, U, V
A tuple of three elements
Triple(1, 2, 3)
// ➔ (1, 2, 3)
Tuple
(any*) -> tuple
A fixed number of heterogeneous elements. Nothing retains its slot, and a tuple whose coordinates are all Missing remains a tuple.
(1, "a", True)
// ➔ (1, "a", true)
tupleFrom
(value*) -> tuple
- arguments 1, … — A collection whose elements go into the tuple in order, or a value that is not a collection, which goes into the tuple as an element. Sample:
[1, 2, 3].
Create a tuple from the elements of a collection.
tupleFrom([1, 2, 3])
// ➔ (1, 2, 3)
The collection must be finite.
tupleFrom(1..3)
// ➔ (1, 2, 3)
MathJSON: TupleFrom
["TupleFrom", xs].
["TupleFrom", ["Range", 1, 3]]
// ➔ ["Tuple", 1, 2, 3]
union
(any+) -> set
- arguments 1, … — A collection whose elements go into the union; an element in several collections appears once. Sample:
Set(1, 2).
Return the union of two or more collections as a set.
union(set(1, 2), set(2, 3))
// ➔ Set(1, 2, 3)
MathJSON: Union • LaTeX: \cup
unique
((xs: T) -> T where T: string) & ((xs: T, test: (character, character) any -> boolean) -> T where T: string) & ((xs: collection<T>) -> list<T> where T: any) & ((xs: collection<T>, test: (T, T) any -> boolean) -> list<T> where T: any)
xs— The collection; the first occurrence of each element is kept, and a string gives a string. Sample:[1, 2, 1, 3].test— A function of two elements that returnsTruewhen they count as the same; by default, two elements are the same when they are equal. Sample:(a, b) => abs(a) == abs(b).
Return a list of the unique elements of the collection.
unique([1, 2, 1, 3, 2])
// ➔ [1,2,3]
The elements keep the order of their first occurrence: unique(xs) is
first(tally(xs)).
unique([5, 2, 10, 18, 5, 2, 5])
// ➔ [5,2,10,18]
With a test of two arguments, an element is kept unless the test holds between an element kept before it and it. A string, with or without a test, gives a string.
unique([1, 2, 3, 4], (a, b) => a % 2 == b % 2)
// ➔ [1,2]
unique("abcab")
// ➔ "abc"
MathJSON: Unique
["Unique", xs], ["Unique", xs, test].
["Unique", ["List", 5, 2, 10, 18, 5, 2, 5]]
// ➔ ["List", 5, 2, 10, 18]
values
(dictionary<any>) -> list
- argument 1 — The dictionary whose values are listed, in the order of its entries. Sample:
{"a" -> 1, "b" -> 2}.
Return a list of the values of a dictionary.
values({"a" -> 1, "b" -> 2})
// ➔ [1,2]
The values are in the iteration order of the dictionary, the order of the
keys.
MathJSON: Values
["Values", dictionary].
["Values", ["Dictionary", ["KeyValuePair", "'a'", 1], ["KeyValuePair", "'b'", 2]]]
// ➔ ["List", 1, 2]
zip
(indexed_collection<any>+) -> list
- arguments 1, … — A collection, one for each coordinate of the tuples; the shortest collection sets the length of the result. Sample:
[1, 2, 3].
Combine multiple collections element-wise into a list of tuples. The result has the length of the shortest input. Nothing retains its coordinate and source position; a row whose coordinates are all Missing remains a tuple.
zip([1, 2, 3], ["a", "b", "c"])
// ➔ [(1, "a"),(2, "b"),(3, "c")]
The n-th tuple holds the n-th element of each collection. The result has
the length of the shortest collection. Its type is
list<tuple<T1, …, Tn>>, where each Ti is the element type of a
collection (unknown for a collection with no element type).
zip([1, 2], ["a", "b"], [True, False, True])
// ➔ [(1, "a", true),(2, "b", false)]
type(zip([1, 2], ["a", "b"]))
// ➔ TypeFrom("list<tuple<integer, string>>")
MathJSON: Zip
["Zip", xs, ys, …].
["Zip", ["List", 1, 2, 3], ["List", 4, 5, 6]]
// ➔ ["List", ["Tuple", 1, 4], ["Tuple", 2, 5], ["Tuple", 3, 6]]