The functions of the core standard library, by module. The boundary is the one the design principles draw (section 2.9): a primitive that touches the system or is sensitive to performance is an operator written in C++, an opaque node of the graph; logic composed from primitives is written in Camel, a subgraph that passes can see into.
How to read an entry:
- Signature:
name: <with-parameters> (parameters) => result. The value a function works on is its ordinary parameter and what configures it is a with-parameter, so calls chain:s->trim->split<','>,xs->filter<p>->sort_by<key>.intis the 64-bit integer andfloatthe 64-bit float;i32andf32are the 32-bit ones.A | Bin a parameter means one overload per type; numeric types are never converted implicitly. - Pure operators depend on their arguments only: a pass may evaluate a call ahead of time,
merge two equal calls or drop an unused one. An operator with effects is left alone, and
its call runs only when it is reachable from a
syncblock or its result is used (design principles 2.1). Every operator of these modules declares which it is. - Failure: a fault stops the program with a located diagnostic (an index out of range, an
argument outside what the operator defines). An error is a value: the function returns
T!and the program handles it with!!,?->ormatch. A result that may not exist isT?, handled with??. An entry without a failure line does not fail. - Write one call that has with-arguments per statement when several appear in one argument
list:
f<a>(x), g<b>(y)is read as comparisons.
Not in this reference: the tensor stack (tensor, nn, autodiff, onnx, sim), the Python
bridge (python, pyplot) and the profiler (perf).
| Module | Import | Written in | Functions |
|---|---|---|---|
| built-in | none | C++ | 47 |
| str | import { ... } from str |
C++ | 20 |
| array | import { ... } from array |
Camel | 17 |
| math | import { ... } from math |
C++ | 45 |
| statistics | import { ... } from statistics |
C++ | 5 |
| algo | import { ... } from algo |
C++ | 12 |
| random | import { ... } from random |
C++ | 7 |
| time | import { ... } from time |
C++ | 3 |
| fs | import { ... } from fs |
C++ | 10 |
| os | import { ... } from os |
C++ | 8 |
| sys | import { ... } from sys |
C++ | 2 |
| json | import { ... } from json |
C++ | 3 |
| re | import { ... } from re |
C++ | 1 |
| crypto | import { ... } from crypto |
C++ | 2 |
| para | import { ... } from para |
C++ | 3 |
| this | import { ... } from this |
C++ | 1 |
The operators behind the language's own operators (+, ==, [], ??, assignment, ...) are
registered under reserved names (__add__, ...) and are not listed here.
Numeric types are never converted implicitly; these functions do it. Converting a float to an integer drops the fraction.
int: (x: i32 | int | f32 | float | string) => int
x as a 64-bit integer.
- Pure.
- Failure: fault
InvalidNumberTextwhen x is a string that is not, as a whole, one integer (blanks and a trailing part included); faultConversionOutOfRangewhen x is a float that is NaN, infinite or beyond the range; use parse_int to handle text in the program. - Example:
int(2.9)gives2
i64: (x: i32 | int | f32 | float | string) => int
The same as int.
- Pure.
- Failure: fault
InvalidNumberTextwhen x is a string that is not, as a whole, one integer; faultConversionOutOfRangewhen x is an int or a float beyond the range of i32, or NaN. - Example:
i64('42')gives42
i32: (x: i32 | int | f32 | float | string) => i32
x as a 32-bit integer.
- Pure.
- Failure: fault
InvalidNumberTextwhen x is a string that is not, as a whole, one integer; faultConversionOutOfRangewhen x is an int or a float beyond the range of i32, or NaN. - Example:
i32(7)gives7
float: (x: i32 | int | f32 | float | string) => float
x as a 64-bit float.
- Pure.
- Failure: fault
InvalidNumberTextwhen x is a string that is not, as a whole, one number; use parse_float to handle that in the program. - Example:
float(3)gives3
f64: (x: i32 | int | f32 | float | string) => float
The same as float.
- Pure.
- Failure: fault
InvalidNumberTextwhen x is a string that is not a number. - Example:
f64('2.5')gives2.5
f32: (x: i32 | int | f32 | float | string) => f32
x as a 32-bit float.
- Pure.
- Failure: fault
InvalidNumberTextwhen x is a string that is not a number. - Example:
f32(0.5)gives0.5
string: (x: any) => string
x as text, as println writes it. A float is written as the shortest text that reads back as the same number: string(2.5) is '2.5', string(2.0) is '2.0'.
- Pure.
- Example:
string(42)gives'42'
parse_int: (text: string) => int!
The integer a text spells, or an error value.
- Pure.
- Failure: error
ParseErrorwhen the text is not, as a whole, one integer (blanks are not skipped). - Example:
parse_int('42') !! 0gives42
parse_float: (text: string) => float!
The number a text spells, or an error value.
- Pure.
- Failure: error
ParseErrorwhen the text is not a number. - Example:
parse_float('2.5') !! 0.0gives2.5
error: (kind: string, message: string) => Error
An Error value of the given kind with the given message; the compiler adds the source
position of the call. throw error(...) returns it from a function declared T!.
- Pure.
- Example:
throw error('RangeError', 'too large')
print: (...args: any) => void
Writes the arguments, separated by spaces, without a line end.
- With effects: writes to standard output.
- Example:
print('a', 1)givesa 1
println: (...args: any) => void
Writes the arguments, separated by spaces, and a line end.
- With effects: writes to standard output.
- Example:
println('a', 1)givesa 1
input: (prompt: string) => string
Writes prompt and reads one line from standard input.
- With effects: reads standard input.
- Example:
input('name: ')giveswhat the user typed
sleep: (milliseconds: int) => void
Suspends the program for the given number of milliseconds.
- With effects: waits.
- Failure: fault
InvalidArgumentwhen the duration is negative. - Example:
sleep(100)
exit: (code: int) => void
Ends the program with the given exit code, after writing buffered output.
- With effects: ends the program.
- Example:
exit(2)
format: <...args: any> (fmt: string) => string
The text fmt with each {} placeholder replaced by the next argument; placeholders take
format specifications such as {:.2f} and {:>8}.
- Pure.
- Failure: fault
FormatFailedwhen the placeholders and the arguments do not fit. - Example:
'{} is {:.2f}'->format<'x', 2.5>gives'x is 2.50'
join: <sep: string> (xs: string[]) => string
The strings of xs joined with sep between them.
- Pure.
- Example:
['a', 'b']->join<', '>gives'a, b'
len: (x: string | T[]) => int
The number of bytes of a string, or of elements of an array.
- Pure.
- Example:
len('h€')gives4
range: (start: int, end: int) => int[]
The integers from start up to, not including, end; empty when end is not above start.
- Pure.
- Example:
range(0, 3)gives[0, 1, 2]
head: (xs: T[]) => T
The first element. An empty array has none: check len first.
- Pure.
- Failure: fault
IndexOutOfRangewhen the array is empty. - Example:
head([1, 2, 3])gives1
tail: (xs: T[]) => T[]
The elements after the first; empty for an array of fewer than two elements.
- Pure.
- Example:
tail([1, 2, 3])gives[2, 3]
slice: <start: int, end: int> (xs: T[]) => T[]
The elements from index start up to, not including, end. Both are positions from 0 to the
length; a bound outside the array (a negative one included) is a fault, as an index out of
range is. take and drop of the module array cut to the array instead.
- Pure.
- Example:
[1, 2, 3, 4]->slice<1, 3>gives[2, 3]
concat: (xs: T[], ys: T[]) => T[]
The elements of xs followed by those of ys, as a new array.
- Pure.
- Example:
concat([1], [2, 3])gives[1, 2, 3]
contains: <value: T> (xs: T[]) => bool
Whether an element of xs equals value, by the == of the element type (by content for
arrays, tuples and structs).
- Pure.
- Example:
[1, 2, 3]->contains<2>givestrue
contains: <sub: string> (s: string) => bool
Whether sub occurs in the string s (bytes are compared). The empty string occurs in every string.
- Pure.
- Example:
'hello'->contains<'ell'>givestrue
zip: (xs: T[], ys: U[]) => (T, U)[]
Two arrays combined element by element into pairs. They must have the same length.
Three or more arrays (zip(xs, ys, zs)) give tuples of that many elements.
- Pure.
- Failure: fault
InvalidArgumentwhen the lengths differ. - Example:
zip([1, 2], ['a', 'b'])gives[(1, 'a'), (2, 'b')]
append: <value: T> (var xs: T[]) => T[]
Adds value at the end of the variable xs, in place, and returns it.
- With effects: changes its argument.
- Example:
append<4>(xs)
extend: <other: T[]> (var xs: T[]) => T[]
Adds the elements of other at the end of the variable xs, in place, and returns it.
- With effects: changes its argument.
- Example:
extend<[4, 5]>(xs)
map and filter apply f to the elements with no order among the calls: the parallel
scheduler may run them at the same time, and the result is by position. foreach and
reduce call f element by element in order. They are declared with effects because what a
call does is what f does.
map: <f: (item: T) => U> (xs: T[]) => U[]
f applied to every element; the calls have no order among them.
- With effects: what f does.
- Example:
[1, 2, 3]->map<(x: int) => x * 2>gives[2, 4, 6]
filter: <f: (item: T) => bool> (xs: T[]) => T[]
The elements for which f is true, in order; the calls of f have no order among them.
- With effects: what f does.
- Example:
[1, 2, 3, 4]->filter<(x: int) => x % 2 == 0>gives[2, 4]
reduce: <f: (acc: U, item: T) => U, initial: U> (xs: T[]) => U
The elements combined from left to right: f(...f(f(initial, xs[0]), xs[1])..., xs[n-1]).
- With effects: what f does.
- Example:
[1, 2, 3]->reduce<(acc: int, x: int) => acc + x, 0>gives6
foreach: <f: (item: T) => void> (xs: T[]) => void
Calls f for every element, in order.
- With effects: what f does.
- Example:
xs->foreach<(x: int) => println(x)>
apply: <f: (item: T) => T> (var xs: T[]) => T[]
Replaces every element of the variable xs by f of it, in place.
- With effects: changes its argument.
- Example:
apply<(x: int) => x * 2>(xs)
A fault (a division by zero, an index out of range, a recursion that is too deep, ...) ends
the program with a located diagnostic. attempt isolates it at the boundary of one call
(design principles 2.9; docs/technical/33_fault_isolation.md). The name is provisional.
attempt: (f: (...args: A) => T, ...args: A) => T!
Calls f with the arguments. A fault raised inside the call becomes an error value whose kind
is the name of the fault (DivisionByZero, ...), with the fault's message and position;
otherwise the result of f. When f itself returns U!, so does attempt. What the call did
before the fault is not undone; exit() and the failures of the compiler itself are not
isolated.
- With effects: what f does.
- Example:
attempt(risky, 0) !! -1 - Example:
attempt(() => xs->map<risky>) !! [-1]
len: (c: Map<K, V> | Set<T>) => int
The number of entries of a map or of elements of a set.
- Pure.
- Example:
len([('a', 1), ('b', 2)] as Map<string, int>)gives2
get: <key: K> (m: Map<K, V>) => V?
The value stored under key, or null when the map has no such key. m[key] is the same lookup.
- Pure.
- Example:
m->get<'z'> ?? 0gives0 when m has no 'z'
get_or: <key: K, fallback: V> (m: Map<K, V>) => V
The value stored under key, or fallback when the map has no such key.
- Pure.
- Example:
m->get_or<'z', -1>gives-1 when m has no 'z'
put: <key: K, value: V> (m: Map<K, V>) => Map<K, V>
A map with value stored under key; an existing entry of that key is replaced. m is unchanged.
- Pure.
- Example:
([('a', 1), ('b', 2)] as Map<string, int>)->put<'c', 3>gives{a: 1, b: 2, c: 3}
remove: <key: K> (c: Map<K, V> | Set<K>) => Map<K, V> | Set<K>
A map without the entry of key, or a set without the element; a key or element that is not there changes nothing. The argument is unchanged.
- Pure.
- Example:
([('a', 1), ('b', 2)] as Map<string, int>)->remove<'a'>gives{b: 2}
has: <key: K> (c: Map<K, V> | Set<K>) => bool
Whether a map has an entry of key, or a set has the element.
- Pure.
- Example:
([('a', 1)] as Map<string, int>)->has<'a'>givestrue
keys: (m: Map<K, V>) => K[]
The keys of a map, in ascending order.
- Pure.
- Example:
keys([('b', 2), ('a', 1)] as Map<string, int>)gives[a, b]
values: (m: Map<K, V>) => V[]
The values of a map, in the ascending order of their keys.
- Pure.
- Example:
values([('b', 2), ('a', 1)] as Map<string, int>)gives[1, 2]
items: (m: Map<K, V>) => (K, V)[]
The entries of a map as (key, value) tuples, in ascending order of the keys.
- Pure.
- Example:
items([('b', 2), ('a', 1)] as Map<string, int>)gives[(a, 1), (b, 2)]
items: (s: Set<T>) => T[]
The elements of a set as an array, in ascending order.
- Pure.
- Example:
items([3, 1, 2] as Set<int>)gives[1, 2, 3]
merge: (m: Map<K, V>, other: Map<K, V>) => Map<K, V>
A map with the entries of both maps; for a key in both, the entry of other is taken. Neither argument is changed.
- Pure.
- Example:
merge(m, n)gives{a: 1, b: 20, c: 30} for m = {a: 1, b: 2}, n = {b: 20, c: 30}
contains: <value: T> (s: Set<T>) => bool
Whether value is an element of the set.
- Pure.
- Example:
([1, 2, 3] as Set<int>)->contains<9>givesfalse
add: <value: T> (s: Set<T>) => Set<T>
A set with value added; s is unchanged.
- Pure.
- Example:
([1, 2, 3] as Set<int>)->add<9>gives{1, 2, 3, 9}
union: (s: Set<T>, other: Set<T>) => Set<T>
The set of the elements that are in either set.
- Pure.
- Example:
union([1, 2, 3] as Set<int>, [3, 4] as Set<int>)gives{1, 2, 3, 4}
intersect: (s: Set<T>, other: Set<T>) => Set<T>
The set of the elements that are in both sets.
- Pure.
- Example:
intersect([1, 2, 3] as Set<int>, [3, 4] as Set<int>)gives{3}
difference: (s: Set<T>, other: Set<T>) => Set<T>
The set of the elements of s that are not in other.
- Pure.
- Example:
difference([1, 2, 3] as Set<int>, [3, 4] as Set<int>)gives{1, 2}
is_subset: (s: Set<T>, other: Set<T>) => bool
Whether every element of s is an element of other.
- Pure.
- Example:
is_subset([1, 2] as Set<int>, [1, 2, 3] as Set<int>)givestrue
A string is stored as bytes: len(s) and s[i] count bytes, and so do the functions of the
first group below. The second group reads and writes a string by Unicode code point (UTF-8).
The string a function works on is its ordinary argument; everything else is a with-argument,
so calls chain: s->trim->split<','>.
split: <sep: string> (s: string) => string[]
The pieces of s between occurrences of sep. An empty s gives one empty piece; a separator at the start or the end gives an empty piece there.
- Pure.
- Failure: fault
InvalidArgumentwhen sep is empty. - Example:
'a,b,,c'->split<','>gives['a', 'b', '', 'c']
trim: (s: string) => string
s without the ASCII white space (space, tab, line feed, carriage return, vertical tab, form feed) at both ends. Other white space, such as U+00A0, is kept.
- Pure.
- Example:
trim(' hi \n')gives'hi'
trim_start: (s: string) => string
s without the ASCII white space at its start.
- Pure.
- Example:
trim_start(' hi ')gives'hi '
trim_end: (s: string) => string
s without the ASCII white space at its end.
- Pure.
- Example:
trim_end(' hi ')gives' hi'
to_upper: (s: string) => string
s with the ASCII letters a-z in upper case. Every other byte is kept as it is, so letters outside ASCII do not change: to_upper('é') is 'é'.
- Pure.
- Example:
to_upper('héllo')gives'HéLLO'
to_lower: (s: string) => string
s with the ASCII letters A-Z in lower case. Every other byte is kept as it is.
- Pure.
- Example:
to_lower('HeLLo')gives'hello'
replace: <from: string, to: string> (s: string) => string
s with every occurrence of from replaced by to, found from left to right without overlap.
- Pure.
- Failure: fault
InvalidArgumentwhen from is empty. - Example:
'a-b-c'->replace<'-', '+'>gives'a+b+c'
find: <sub: string> (s: string) => int?
The byte index of the first occurrence of sub in s, or null when there is none. An empty sub is found at 0.
- Pure.
- Example:
'hello'->find<'l'> ?? -1gives2
substr: <start: int, length: int> (s: string) => string
The length bytes of s that start at byte start.
- Pure.
- Failure: fault
IndexOutOfRangewhen start or start + length lies outside the string; faultInvalidArgumentwhen length is negative. - Example:
'hello'->substr<1, 3>gives'ell'
starts_with: <prefix: string> (s: string) => bool
Whether s begins with prefix. Every string begins with the empty string.
- Pure.
- Example:
'hello'->starts_with<'he'>givestrue
ends_with: <suffix: string> (s: string) => bool
Whether s ends with suffix.
- Pure.
- Example:
'hello'->ends_with<'lo'>givestrue
repeat: <count: int> (s: string) => string
s written count times in a row.
- Pure.
- Failure: fault
InvalidArgumentwhen count is negative or the result would be longer than a string can be (4 GiB). - Example:
'ab'->repeat<3>gives'ababab'
bytes: (s: string) => int[]
The bytes of s as numbers 0 to 255.
- Pure.
- Example:
bytes('hé')gives[104, 195, 169]
from_bytes: (xs: int[]) => string
The string made of the given bytes. The result need not be valid UTF-8.
- Pure.
- Failure: fault
InvalidArgumentwhen an element is not in 0 to 255. - Example:
from_bytes([104, 105])gives'hi'
A string need not be valid UTF-8, so a function that decodes it can fail: it returns T!
with an error of kind EncodingError. Decoding is strict: overlong forms, surrogates
(U+D800 to U+DFFF), values above U+10FFFF, stray continuation bytes and sequences cut short
are all invalid. An index out of range is a fault, as everywhere.
is_valid_utf8: (s: string) => bool
Whether s is valid UTF-8. The empty string is.
- Pure.
- Example:
is_valid_utf8(from_bytes([255]))givesfalse
codepoints: (s: string) => int[]!
The code points of s.
- Pure.
- Failure: error
EncodingErrorwhen s is not valid UTF-8. - Example:
codepoints('h€') !! [0]gives[104, 8364]
from_codepoints: (xs: int[]) => string!
The string made of the given code points, encoded as UTF-8.
- Pure.
- Failure: error
EncodingErrorwhen an element is not a code point (negative, above 0x10FFFF, or a surrogate). - Example:
from_codepoints([104, 8364]) !! ''gives'h€'
char_count: (s: string) => int!
The number of code points in s (len(s) is the number of bytes).
- Pure.
- Failure: error
EncodingErrorwhen s is not valid UTF-8. - Example:
char_count('h€') !! -1gives2
char_at: <index: int> (s: string) => string!
The code point number index of s, as a string.
- Pure.
- Failure: error
EncodingErrorwhen s is not valid UTF-8; faultIndexOutOfRangewhen index is not below the number of code points. - Example:
'h€'->char_at<1> !! '?'gives'€'
char_substr: <start: int, count: int> (s: string) => string!
The count code points of s that start at code point start.
- Pure.
- Failure: error
EncodingErrorwhen s is not valid UTF-8; faultIndexOutOfRangewhen start or start + count lies outside the string; faultInvalidArgumentwhen count is negative. - Example:
'h€llo'->char_substr<1, 2> !! '?'gives'€l'
Array functions and higher-order functions, written in Camel on top of the built-in operators (map, filter, reduce, range, zip, slice, len) and three primitives of the algo module (flatten, unique, argsort). Every function returns a new value; none changes its argument.
- The array a function works on is its ordinary argument; a function or a value that
configures it is a with-argument, as for the built-in
map<f>(xs)andslice<a, b>(xs), so calls chain:xs->filter<p>->sort_by<key>->take<3>. - A result that may not exist is
T?(find,index_of,min,max). Nothing here returns an error value, and a wrong argument is a fault of the operator that meets it. - Order of evaluation (design principles 2.7). A function passed to one of these is applied
with
map: its calls on different elements have NO order among them and the parallel scheduler may run them at the same time; the result is put together by position and is the same on every back end. That holds forfind,any,all,count,flat_map,sort_byandzip_with. None of them stops early: the function is applied to every element. A function with side effects belongs inforeachorreduce, which are ordered. - These are generic functions: each call builds the instance for its element types in the
module that calls it (DESIGN-QUESTION(generic-export)).
group_byis not here: it needs the map type.
reverse: (xs: (typeas T)[]) => T[]
The elements in reverse order.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
reverse([1, 2, 3])gives[3, 2, 1]
take: <n: int> (xs: (typeas T)[]) => T[]
The first n elements; all of them when there are fewer, none when n is not positive.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
[1, 2, 3, 4]->take<2>gives[1, 2]
drop: <n: int> (xs: (typeas T)[]) => T[]
The elements after the first n; none when there are fewer, all when n is not positive.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
[1, 2, 3, 4]->drop<1>gives[2, 3, 4]
enumerate: (xs: (typeas T)[]) => (int, T)[]
Each element with its index.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
enumerate(['a', 'b'])gives[(0, 'a'), (1, 'b')]
flatten: (xss: (typeas T)[][]) => T[]
The elements of the inner arrays, in order. (Primitive: algo::flatten.)
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
flatten([[1, 2], [3]])gives[1, 2, 3]
unique: (xs: (typeas T)[]) => T[]
The first occurrence of every value, in order; values are compared as == compares them.
(Primitive: algo::unique.)
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
unique([3, 1, 3, 2, 1])gives[3, 1, 2]
index_of: <x: typeas T> (xs: T[]) => int?
The index of the first element equal to x, or null.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
[3, 9, 2]->index_of<9> ?? -1gives1
find: <pred: (x: typeas T) => bool> (xs: T[]) => T?
The first element for which pred is true, or null.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
[3, 9, 2]->find<(x: int) => x > 4> ?? -1gives9
any: <pred: (x: typeas T) => bool> (xs: T[]) => bool
True when pred is true for at least one element; false for an empty array.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
[3, 9, 2]->any<(x: int) => x > 4>givestrue
all: <pred: (x: typeas T) => bool> (xs: T[]) => bool
True when pred is true for every element; true for an empty array.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
[3, 9, 2]->all<(x: int) => x > 4>givesfalse
count: <pred: (x: typeas T) => bool> (xs: T[]) => int
The number of elements for which pred is true.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
[3, 9, 2]->count<(x: int) => x > 2>gives2
sum: (xs: int[]) => int
sum: (xs: float[]) => float
sum: (xs: i32[]) => i32
sum: (xs: f32[]) => f32
The sum of the elements, 0 for an empty array. One function per numeric type (the zero of a
type variable cannot be written). Integers wrap around on overflow, as + does.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
sum([1, 2, 3])gives6
min: (xs: (typeas T)[]) => T?
The smallest element by < (numbers, or strings by byte), or null for an empty array;
among equal elements the first. A NaN compares false with everything: it is the result only
when it is the first element.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
min([3, 9, 2]) ?? 0gives2
max: (xs: (typeas T)[]) => T?
The largest element by >, or null for an empty array; among equal elements the first.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
max(['pear', 'fig']) ?? ''gives'pear'
flat_map: <f: (x: typeas T) => (typeas U)[]> (xs: T[]) => U[]
f applied to every element, the resulting arrays joined in order.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
[1, 2]->flat_map<(x: int) => [x, x * 10]>gives[1, 10, 2, 20]
sort_by: <key: (x: typeas T) => typeas K> (xs: T[]) => T[]
The elements in ascending order of key(x); elements with equal keys keep their order (the sort is stable, so sorting by one key and then by another works). A key is a number, a string (ordered by byte) or a bool; NaN keys come last. For a descending order of numbers use the negated key. (Primitive: algo::argsort.)
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Example:
['pear', 'fig', 'apple']->sort_by<(w: string) => len(w)>gives['fig', 'pear', 'apple']
zip_with: <f: (a: typeas T, b: typeas U) => typeas V> (xs: T[], ys: U[]) => V[]
f(xs[i], ys[i]) for every i.
- Written in Camel: a subgraph, pure when the functions passed to it are.
- Failure: fault
InvalidArgument(of zip) when the two arrays differ in length. - Example:
zip_with<add>([1, 2], [10, 20])gives[11, 22]
Numeric types are not converted implicitly. A function over floats takes f32 or float
and returns the type it was given; a function of several numbers takes numbers of one type.
Outside its domain a float function gives the IEEE result (NaN or an infinity), not a fault.
A constant is a function of no arguments: pi().
pi: () => float
The ratio of a circle's circumference to its diameter.
- Pure.
- Example:
pi()gives3.14159...
e: () => float
The base of the natural logarithm.
- Pure.
- Example:
log(e())gives1
inf: () => float
Positive infinity; negative infinity is -inf().
- Pure.
- Example:
is_inf(-inf())givestrue
nan: () => float
A NaN. It equals nothing, itself included: test with is_nan.
- Pure.
- Example:
is_nan(nan())givestrue
abs: (x: i32 | int | f32 | float) => i32 | int | f32 | float
The absolute value. The smallest integer has no positive counterpart: its absolute value is not defined.
- Pure.
- Example:
abs(-3)gives3
sqrt: (x: i32 | int | f32 | float) => f32 | float
The square root. An integer argument is converted: i32 gives f32, int gives float.
- Pure.
- Example:
sqrt(9.0)gives3
exp: (x: f32 | float) => f32 | float
e raised to the power x.
- Pure.
- Example:
exp(0.0)gives1
expm1: (x: f32 | float) => f32 | float
exp(x) - 1, accurate for x near 0.
- Pure.
- Example:
expm1(0.0)gives0
log: (x: f32 | float) => f32 | float
The natural logarithm. log(0.0) is -inf, the logarithm of a negative number is NaN.
- Pure.
- Example:
log(1.0)gives0
log2: (x: f32 | float) => f32 | float
The logarithm to base 2.
- Pure.
- Example:
log2(8.0)gives3
log10: (x: f32 | float) => f32 | float
The logarithm to base 10.
- Pure.
- Example:
log10(1000.0)gives3
log1p: (x: f32 | float) => f32 | float
log(1 + x), accurate for x near 0.
- Pure.
- Example:
log1p(0.0)gives0
pow: (x: f32 | float, y: f32 | float) => f32 | float
x raised to the power y. pow(0.0, 0.0) is 1; a negative x with a fractional y gives NaN.
- Pure.
- Example:
pow(2.0, 10.0)gives1024
hypot: (x: f32 | float, y: f32 | float) => f32 | float
The square root of xx + yy, without overflow in the squares.
- Pure.
- Example:
hypot(3.0, 4.0)gives5
sin: (x: f32 | float) => f32 | float
The sine of x, x in radians.
- Pure.
- Example:
sin(0.0)gives0
cos: (x: f32 | float) => f32 | float
The cosine of x, x in radians.
- Pure.
- Example:
cos(0.0)gives1
tan: (x: f32 | float) => f32 | float
The tangent of x, x in radians.
- Pure.
- Example:
tan(0.0)gives0
asin: (x: f32 | float) => f32 | float
The arc sine, in radians; NaN outside -1 to 1.
- Pure.
- Example:
asin(1.0)gives1.5708
acos: (x: f32 | float) => f32 | float
The arc cosine, in radians; NaN outside -1 to 1.
- Pure.
- Example:
acos(1.0)gives0
atan: (x: f32 | float) => f32 | float
The arc tangent, in radians.
- Pure.
- Example:
atan(1.0)gives0.785398
atan2: (y: f32 | float, x: f32 | float) => f32 | float
The angle of the point (x, y) in radians, between -pi and pi. Note the order: y first.
- Pure.
- Example:
atan2(1.0, 1.0)gives0.785398
sinh: (x: f32 | float) => f32 | float
The hyperbolic sine.
- Pure.
- Example:
sinh(0.0)gives0
cosh: (x: f32 | float) => f32 | float
The hyperbolic cosine.
- Pure.
- Example:
cosh(0.0)gives1
tanh: (x: f32 | float) => f32 | float
The hyperbolic tangent.
- Pure.
- Example:
tanh(0.0)gives0
floor: (x: f32 | float) => f32 | float
The largest whole number not above x, as a float.
- Pure.
- Example:
floor(-2.5)gives-3
ceil: (x: f32 | float) => f32 | float
The smallest whole number not below x, as a float.
- Pure.
- Example:
ceil(2.1)gives3
round: (x: f32 | float) => f32 | float
The nearest whole number, halves away from zero, as a float.
- Pure.
- Example:
round(2.5)gives3
trunc: (x: f32 | float) => f32 | float
x without its fraction (rounded toward zero), as a float.
- Pure.
- Example:
trunc(-2.7)gives-2
min: (a: i32 | int | f32 | float, b: i32 | int | f32 | float) => i32 | int | f32 | float
The smaller of two numbers of one type. With a NaN on either side the result is NaN.
- Pure.
- Example:
min(3, 5)gives3
max: (a: i32 | int | f32 | float, b: i32 | int | f32 | float) => i32 | int | f32 | float
The larger of two numbers of one type. With a NaN on either side the result is NaN.
- Pure.
- Example:
max(3, 5)gives5
clamp: (x: i32 | int | f32 | float, lo: i32 | int | f32 | float, hi: i32 | int | f32 | float) => i32 | int | f32 | float
x held between lo and hi: lo when x is below, hi when above. A NaN x stays NaN.
- Pure.
- Failure: fault
InvalidArgumentwhen lo is above hi, or a bound is NaN. - Example:
clamp(15, 0, 10)gives10
sign: (x: i32 | int | f32 | float) => i32 | int | f32 | float
-1, 0 or 1 by the sign of x, in the type of x. The sign of a NaN is NaN.
- Pure.
- Example:
sign(-2.5)gives-1
is_nan: (x: f32 | float) => bool
Whether x is a NaN.
- Pure.
- Example:
is_nan(inf() - inf())givestrue
is_inf: (x: f32 | float) => bool
Whether x is positive or negative infinity.
- Pure.
- Example:
is_inf(1.0)givesfalse
gcd: (a: i32 | int, b: i32 | int) => i32 | int
The greatest common divisor, never negative; gcd(0, 0) is 0.
- Pure.
- Failure: fault
InvalidArgumentwhen the result does not fit the type (the smallest integer with itself or with 0). - Example:
gcd(12, 18)gives6
lcm: (a: i32 | int, b: i32 | int) => i32 | int
The least common multiple, never negative; 0 when either argument is 0.
- Pure.
- Failure: fault
InvalidArgumentwhen the result does not fit the type. - Example:
lcm(4, 6)gives12
bin: (x: i32 | int) => string
The digits of x in base 2 with the prefix 0b; a negative number is shown as its 64-bit two's complement.
- Pure.
- Example:
bin(5)gives'0b101'
oct: (x: i32 | int) => string
The digits of x in base 8 with the prefix 0o.
- Pure.
- Example:
oct(8)gives'0o10'
hex: (x: i32 | int) => string
The digits of x in base 16, in upper case, with the prefix 0x.
- Pure.
- Example:
hex(255)gives'0xFF'
Bit operations are functions, not operators. Integers are two's complement: int has 64
bits, i32 has 32.
bit_and: (a: i32 | int, b: i32 | int) => i32 | int
The bits set in both a and b.
- Pure.
- Example:
bit_and(12, 10)gives8
bit_or: (a: i32 | int, b: i32 | int) => i32 | int
The bits set in a or in b.
- Pure.
- Example:
bit_or(12, 10)gives14
bit_xor: (a: i32 | int, b: i32 | int) => i32 | int
The bits set in exactly one of a and b.
- Pure.
- Example:
bit_xor(12, 10)gives6
bit_not: (x: i32 | int) => i32 | int
Every bit of x inverted; the same as the operator ~.
- Pure.
- Example:
bit_not(0)gives-1
shl: (x: i32 | int, count: i32 | int) => i32 | int
x shifted left by count bits: bits shifted out are lost and zeros come in, so the sign may change. The count may be of either integer type.
- Pure.
- Failure: fault
InvalidArgumentwhen count is negative or not below the width of x (64 for int, 32 for i32). - Example:
shl(1, 4)gives16
shr: (x: i32 | int, count: i32 | int) => i32 | int
x shifted right by count bits, keeping the sign (an arithmetic shift): shr(-8, 1) is -4.
- Pure.
- Failure: fault
InvalidArgumentwhen count is negative or not below the width of x. - Example:
shr(256, 4)gives16
Every function takes an array of numbers of one type (i32, int, f32 or float) and computes in float.
mean: (xs: (i32 | int | f32 | float)[]) => float
The arithmetic mean; 0 for an empty array.
- Pure.
- Example:
mean([1, 2, 3, 4])gives2.5
stdev: (xs: (i32 | int | f32 | float)[]) => float
The sample standard deviation (divisor n - 1); 0 for fewer than two elements.
- Pure.
- Example:
stdev([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0])gives2.13809
variance: (xs: (i32 | int | f32 | float)[]) => float
The sample variance (divisor n - 1), the square of stdev; 0 for fewer than two elements.
- Pure.
- Example:
variance([1, 2, 3, 4])gives1.66667
median: (xs: (i32 | int | f32 | float)[]) => float?
The middle value of the sorted elements, the mean of the two middle ones for an even count; null for an empty array, NaN when an element is NaN.
- Pure.
- Example:
median([3, 1, 2]) ?? 0.0gives2
quantile: <q: float> (xs: (i32 | int | f32 | float)[]) => float?
The q-quantile, q from 0 to 1, by linear interpolation between the two nearest ranks (position q * (n - 1) of the sorted elements); null for an empty array, NaN when an element is NaN.
- Pure.
- Failure: fault
InvalidArgumentwhen q is not between 0 and 1. - Example:
[1.0, 2.0, 3.0, 4.0, 5.0]->quantile<0.25> ?? 0.0gives2
Sorting works on arrays of numbers (i32, int, f32, float) in ascending order. Each algorithm
comes in two forms: xxx_sorted returns a new array, xxx_sort sorts a var array in place.
To sort anything else, or by a key, use sort_by of the array module.
sorted: (xs: T[]) => T[]
A sorted copy of xs (quicksort).
- Pure.
- Failure: fault
OperandTypeUnsupportedwhen the elements are not numbers. - Example:
sorted([3, 1, 2])gives[1, 2, 3]
insert_sorted: (xs: T[]) => T[]
A sorted copy of xs, by insertion sort.
- Pure.
- Failure: fault
OperandTypeUnsupportedwhen the elements are not numbers. - Example:
insert_sorted([3, 1, 2])gives[1, 2, 3]
quick_sorted: (xs: T[]) => T[]
A sorted copy of xs, by quicksort.
- Pure.
- Failure: fault
OperandTypeUnsupportedwhen the elements are not numbers. - Example:
quick_sorted([3, 1, 2])gives[1, 2, 3]
merge_sorted: (xs: T[]) => T[]
A sorted copy of xs, by merge sort.
- Pure.
- Failure: fault
OperandTypeUnsupportedwhen the elements are not numbers. - Example:
merge_sorted([3, 1, 2])gives[1, 2, 3]
sort: (var xs: T[]) => T[]
Sorts xs in place (quicksort) and returns it.
- With effects: changes its argument.
- Failure: fault
OperandTypeUnsupportedwhen the elements are not numbers. - Example:
sort(xs)givesxs is now sorted
insert_sort: (var xs: T[]) => T[]
Sorts xs in place by insertion sort and returns it.
- With effects: changes its argument.
- Failure: fault
OperandTypeUnsupportedwhen the elements are not numbers. - Example:
insert_sort(xs)givesxs is now sorted
quick_sort: (var xs: T[]) => T[]
Sorts xs in place by quicksort and returns it.
- With effects: changes its argument.
- Failure: fault
OperandTypeUnsupportedwhen the elements are not numbers. - Example:
quick_sort(xs)givesxs is now sorted
merge_sort: (var xs: T[]) => T[]
Sorts xs in place by merge sort and returns it.
- With effects: changes its argument.
- Failure: fault
OperandTypeUnsupportedwhen the elements are not numbers. - Example:
merge_sort(xs)givesxs is now sorted
merge_sorted_arrays: (left: T[], right: T[]) => T[]
The sorted array made of the elements of two sorted arrays of numbers.
- Pure.
- Failure: fault
OperandTypeUnsupportedwhen the elements are not numbers. - Example:
merge_sorted_arrays([1, 4], [2, 3])gives[1, 2, 3, 4]
flatten: (xss: T[][]) => T[]
The elements of the inner arrays, in order. The primitive behind flatten and flat_map
of the array module.
- Pure.
- Example:
flatten([[1, 2], [3]])gives[1, 2, 3]
unique: (xs: T[]) => T[]
The first occurrence of every value, in order; values are compared as == compares them
(a NaN equals nothing, so every NaN is kept). The primitive behind unique of the array
module.
- Pure.
- Example:
unique([3, 1, 3, 2, 1])gives[3, 1, 2]
argsort: (keys: (i32 | int | f32 | float | bool | string)[]) => int[]
The positions of the keys in ascending order of key; equal keys keep their order (a stable
sort). Keys are numbers, strings (ordered by byte) or bools; NaN keys come last. The
primitive behind sort_by of the array module.
- Pure.
- Example:
argsort([30, 10, 20])gives[1, 2, 0]
One generator for the whole process. Every function reads or advances it and is declared with effects; none is ever folded or merged by a pass.
seed: (value: int) => void
Sets the state of the generator: the same seed gives the same sequence.
- With effects: sets the generator.
- Example:
seed(42)
rand: () => float
A float drawn uniformly from 0 (included) to 1 (excluded).
- With effects: advances the generator.
- Example:
rand()gives0.374540
randn: () => float
A float drawn from the normal distribution with mean 0 and deviation 1.
- With effects: advances the generator.
- Example:
randn()gives-0.138264
randint: (low: int, high: int) => int
An integer drawn uniformly from low to high, both included; the two are swapped when low is above high.
- With effects: advances the generator.
- Example:
randint(1, 6)gives4
choice: (xs: T[]) => T
One element of xs, drawn uniformly.
- With effects: advances the generator.
- Failure: fault
InvalidArgumentwhen xs is empty. - Example:
choice(['a', 'b', 'c'])gives'b'
sample: (xs: T[], n: int) => T[]
n elements of xs drawn without replacement, as a new array.
- With effects: advances the generator.
- Failure: fault
InvalidArgumentwhen n is negative or above the number of elements. - Example:
sample([1, 2, 3, 4], 2)gives[3, 1]
shuffle: (xs: T[]) => T[]
The elements of xs in a random order, as a new array; xs is not changed.
- With effects: advances the generator.
- Example:
shuffle([1, 2, 3])gives[2, 3, 1]
All three are declared with effects: now reads the clock, and strptime reads the time zone
of the process. strftime formats in UTC and is kept with them.
now: () => float
The current time in seconds since 1970-01-01 00:00 UTC, with a fraction.
- With effects: reads the clock.
- Example:
now()gives1791806400.25
strftime: (timestamp: float, format: string) => string
The time timestamp (seconds since the epoch) written with a strftime format, in UTC.
- With effects: declared with effects together with the rest of the module.
- Failure: fault
TimeFormatFailedwhen the time or the format cannot be used. - Example:
strftime(0.0, '%Y-%m-%d')gives'1970-01-01'
strptime: (text: string, format: string) => float
The time, in seconds since the epoch, that text gives when read with a strptime format; the fields are taken as local time.
- With effects: reads the time zone.
- Failure: fault
TimeFormatFailedwhen text does not have the format. - Example:
strptime('1970-01-02', '%Y-%m-%d')gives86400 in UTC
Every function touches the file system and is declared with effects: its call must be reachable from a sync block to run, and no pass folds or merges it.
read_text: (path: string) => string
The whole content of the file.
- With effects: reads a file.
- Failure: fault
FileOpenFailedwhen the file cannot be opened; use try_read_text to handle that in the program. - Example:
read_text('notes.txt')givesthe text of the file
try_read_text: (path: string) => string!
The whole content of the file, or an error value.
- With effects: reads a file.
- Failure: error
IOErrorwhen the path is a directory, or the file cannot be opened or read. - Example:
try_read_text('notes.txt') !! ''givesthe text, or '' when it cannot be read
read_chunk: (path: string, offset: int, size: int) => string
Up to size bytes of the file starting at byte offset; fewer at the end of the file.
- With effects: reads a file.
- Failure: fault
InvalidArgumentwhen offset or size is negative; faultFileOpenFailedorFileSystemErrorwhen the file cannot be opened or read. - Example:
read_chunk('notes.txt', 0, 16)givesthe first 16 bytes
write_text: (path: string, content: string) => void
Replaces the content of the file, creating it and its parent directories when needed.
- With effects: writes a file.
- Failure: fault
FileSystemErrorwhen a directory cannot be created; faultFileOpenFailedwhen the file cannot be opened. - Example:
write_text('out/log.txt', 'done')
exists: (path: string) => bool
Whether something exists at the path.
- With effects: reads the file system.
- Example:
exists('notes.txt')givestrue or false
is_file: (path: string) => bool
Whether the path names a regular file.
- With effects: reads the file system.
- Example:
is_file('notes.txt')givestrue or false
is_dir: (path: string) => bool
Whether the path names a directory.
- With effects: reads the file system.
- Example:
is_dir('out')givestrue or false
file_size: (path: string) => int
The size of the file in bytes.
- With effects: reads the file system.
- Failure: fault
FileSystemErrorwhen the size cannot be read (no such file). - Example:
file_size('notes.txt')gives1024
mkdir: (path: string) => bool
Creates one directory; false when it already exists.
- With effects: changes the file system.
- Failure: fault
FileSystemErrorwhen it cannot be created (no parent directory). - Example:
mkdir('out')givestrue
mkdirs: (path: string) => bool
Creates a directory and every missing parent; false when it already exists.
- With effects: changes the file system.
- Failure: fault
FileSystemErrorwhen it cannot be created. - Example:
mkdirs('out/logs/today')givestrue
Every function touches the process, the terminal or the machine and is declared with effects.
sleep and exit are also built in: they need no import.
sleep: (milliseconds: int) => void
Suspends the program for the given number of milliseconds.
- With effects: waits.
- Failure: fault
InvalidArgumentwhen the duration is negative. - Example:
sleep(100)
whoami: () => string
The name of the user the process runs as.
- With effects: reads the environment.
- Failure: fault
RuntimeErrorwhen the name cannot be found. - Example:
whoami()gives'alice'
cpu_count: () => int
The number of hardware threads, at least 1.
- With effects: reads the machine.
- Example:
cpu_count()gives8
set_terminal_raw_mode: (enabled: bool) => void
Switches the terminal to raw mode (keys arrive one by one, unechoed) or back.
- With effects: changes the terminal.
- Failure: fault
RuntimeErrorwhen the terminal refuses. - Example:
set_terminal_raw_mode(true)
has_input: () => bool
Whether a key press is waiting to be read.
- With effects: reads the terminal.
- Example:
has_input()givestrue or false
get_char: () => string
One character of pending terminal input.
- With effects: reads the terminal.
- Example:
get_char()gives'w'
get_chars: (max: int) => string
Up to max characters of pending terminal input.
- With effects: reads the terminal.
- Example:
get_chars(3)givesat most three characters
clear_input_buffer: () => void
Discards the terminal input that is waiting.
- With effects: reads the terminal.
- Example:
clear_input_buffer()
Both functions read the environment of the process and are declared with effects.
get_env: (name: string) => string
The value of an environment variable, or the empty string when it is not set.
- With effects: reads the environment.
- Example:
get_env('HOME')gives'/home/alice'
get_cwd: () => string
The current working directory.
- With effects: reads the environment.
- Example:
get_cwd()gives'/home/alice/project'
encode: (value: any) => string
The JSON text of a value, on one line.
- Pure.
- Failure: fault
JsonEncodeUnsupportedwhen the value has a type JSON cannot hold. - Example:
encode([1, 2])gives'[1,2]'
encode: (value: any, indent: int) => string
The JSON text of a value, indented by indent spaces per level; a negative indent gives one line.
- Pure.
- Failure: fault
JsonEncodeUnsupportedwhen the value has a type JSON cannot hold. - Example:
encode([1, 2], 2)gives'[\n 1,\n 2\n]'
decode: (text: string) => any
The value a JSON text describes. Its static type is any.
- Pure.
- Failure: fault
JsonDecodeFailedwhen the text is not JSON. - Example:
decode('[1, 2]')givesan array of 1 and 2, typed any
decode_as: <shape: any> (text: string) => any
The value a JSON text describes, decoded to the type of shape; the value of shape is not
read. The result is an error value when the text does not have that type.
the mismatch; error value JsonDecodeFailed when the text is not JSON
- Pure.
- Failure: error value
JsonTypeErrorwhen the text is JSON of another type, with the path of. - Example:
decode_as<[] as Map<string, int>>('{"a": 1}')gives{a: 1}
test: (pattern: string, text: string) => bool
Whether the regular expression (ECMAScript syntax) matches somewhere in text.
- Pure.
- Failure: fault
RegexInvalidwhen pattern is not a regular expression. - Example:
test('[0-9]+', 'room 42')givestrue
sha256: (s: string) => string
The SHA-256 digest of the bytes of s, as 64 lower-case hexadecimal digits.
- Pure.
- Example:
sha256('abc')gives'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'
sha256_rounds: (s: string, rounds: int) => string
SHA-256 applied rounds times, each round to the hexadecimal text of the one before; 0 rounds gives s itself.
- Pure.
- Failure: fault
InvalidArgumentwhen rounds is negative. - Example:
sha256_rounds('abc', 1) == sha256('abc')givestrue
The unordered counterparts of the built-in foreach and reduce: the scheduler may run the
calls of the function in any order and at the same time.
unordered_foreach: <f: (item: T) => void> (xs: T[]) => void
Calls f for every element; the calls have no order among them.
- With effects: what f does.
- Example:
xs->unordered_foreach<work>
unordered_reduce: <f: (acc: T, item: T) => T, initial: T> (xs: T[]) => T
Combines the elements with f starting from initial; the order in which elements are combined is not fixed, so f should be associative and commutative.
- With effects: what f does.
- Example:
xs->unordered_reduce<add, 0>
rendezvous: (parties: int, timeout_ms: int) => int
Blocks until parties calls are waiting at the one meeting point of the process, or until
timeout_ms milliseconds have passed; returns how many calls met (after a timeout, how many
were waiting). A tool for showing that calls really run at the same time.
- With effects: waits for other calls.
- Failure: fault
RuntimeErrorwhen parties is below 1 or timeout_ms is negative. - Example:
rendezvous(2, 1000)gives2 when another call arrived in time
zen: () => string
The Zen of Camel, the text of the file ZEN.
- Pure.
- Example:
println(zen())