Core
The core library holds the operations that every program uses: the markers for absent values, declarations and assignments, the inspection and control of evaluation, comparison, errors, types as values, strings, and the conversion to and from LaTeX. This introduction gives the concepts you need before you read the entries.
Syntax and library names
Many core definitions are the engine form of an Epsil construct. You write the construct, and the engine receives the definition. The entries list these definitions under their MathJSON name.
| Epsil syntax | Definition |
|---|---|
let x = 3, const c = 1 | Declare |
x = x + 1 | Assign |
f(x) = x^2, function f(x) { … } | DefineFunction |
x => x^2 | Function |
xs |> sort | Pipe |
f(...t) | Spread |
f(rate: 0.05) | NamedArgument |
x is integer | MatchesType |
type point = tuple<x: number, y: number> | DeclareType |
type shape = circle(r: number) | square(s: number) | DeclareSumType |
protocol Area { … } | DeclareProtocol |
type string is Copyable | DeclareConformance |
A library name with a lowercase Epsil spelling (head for Head,
simplify for Simplify, missing for Missing) is shown with that
spelling. A name without one (Hold, HoldValues, Subtype, Latex, N)
keeps its MathJSON spelling.
Absent values
Three values mark that a value is absent. They do not behave the same way.
| Value | Meaning |
|---|---|
nothing | The value of an empty block or of a statement with no value. It is kept where it is written. |
missing | A position exists, but its value is absent (R NA, Julia missing). |
NaN | A number that is not defined (Not a Number). |
nothing is kept where it is written, and an arithmetic operation on it is a
type error. missing keeps its position, and an arithmetic operation on it
gives missing:
[12, nothing, 34]
// ➔ [12,nothing,34]
[missing + 1, 2]
// ➔ [missing,2]
isMissing is true for missing and NaN. Coalesce returns
the first operand that is not absent:
Coalesce(missing, NaN, 3, 4)
// ➔ 3
Declaring, assigning and assuming
let declares a name whose value can change, and const declares a name
whose value cannot change. The = operator gives a new value to a name that
let declared. The value is evaluated when the assignment is evaluated.
const c = 299792458
let t = 2
t = t + 1
c * t
// ➔ 899377374
Once a name has a type, a new value must be compatible with that type. A name that has no value is a free symbol: it stays symbolic in expressions.
assume records a fact about a symbol, for example that it is positive. It
does not declare the symbol. It evaluates to a string that reports the
outcome: "ok" when the fact was recorded, "tautology" when the known
facts already imply it, "contradiction" when it conflicts with them, and
"not-a-predicate" when the argument is not a condition.
[assume(x > 0), assume(x > -1), assume(x < 0), assume(42)]
// ➔ ["ok", "tautology", "contradiction", "not-a-predicate"]
HoldValues evaluates an expression as if some names had no value. The
declared type and the assumptions of each name still apply. With one
argument, every name that has a value is held. With a list as the second
argument, only the names in the list are held:
let x = 5
let y = 2
(x + y, HoldValues(x + y), HoldValues(x + y, [y]))
// ➔ (7, x + y, y + 5)
The structure of an expression
An expression has a head, the name of its operator, and a tail, its
operands. head and tail read the expression as it is written, before
the operands are evaluated:
head(x^2)
// ➔ Power
[tail(1 + x)]
// ➔ [1, x]
Hold keeps an expression in its written form: the expression is not
evaluated until ReleaseHold removes the Hold.
Hold(1 + 2)
// ➔ Hold(1 + 2)
ReleaseHold(Hold(1 + 2))
// ➔ 3
A function declared with hold receives each argument as it is written, not
its value. Its body can then inspect the expression:
let a = 3
hold f(e) = head(e)
f(a + 1)
// ➔ Add
Comparing expressions
The == operator compares values. It approximates an exact value when
the other operand is a float, and it uses no tolerance: 1e-12 == 0 is
false. The === operator compares the expressions as they are
written (after canonicalization). It never evaluates and never reads the
value of a declared or assigned name.
(sin(pi) == 0, sin(pi) === 0, 1e-12 == 0, 1e-12 > 0)
// ➔ (true, false, false, true)
let x = 5
(x == 5, x === 5)
// ➔ (true, false)
A parameter of a function, and the variable of a for loop or of a
comprehension, is replaced by its argument before the comparison, so ===
can be used in a predicate:
filter([1, 2, 3], e => e === 2)
// ➔ [2]
=== always gives True or False. == can stay unevaluated when the
answer is not known, for example x == y with two free symbols. NaN is not
equal to itself with ==, but it is the same as itself with ===:
(NaN == NaN, NaN === NaN)
// ➔ (false, true)
Exact evaluation and approximation
Evaluation is exact. A result that has no exact decimal form stays symbolic:
ln(2)
// ➔ ln(2)
N gives a numeric approximation. A second argument sets the number of
significant digits:
N(ln(2))
// ➔ 0.693147180559945309417
N(pi, 20)
// ➔ 3.1415926535897932385
simplify changes an expression to a simpler form, and solve finds the
values of an unknown that make an equation true:
simplify(sin(x)^2 + cos(x)^2)
// ➔ 1
solve(x^2 - 5x + 6 == 0, x)
// ➔ [3, 2]
Errors are values
A problem at run time, such as an argument of the wrong type, does not stop
the program. It gives an Error value. The error goes up through the
expressions that contain it, and becomes their value. isError tests for an
error value:
isError(ln("a"))
// ➔ true
To make an error value of your own, use RuntimeError. Its argument is a
code string, or an ErrorCode("code", details…) expression when the error
carries data. Do not write Error(…) for this: a written Error marks the
program itself as wrong.
function reciprocal(x) {
if x == 0 { RuntimeError("zero-has-no-reciprocal") } else { 1 / x }
}
[reciprocal(4), reciprocal(0)]
// ➔ [1/4, Error("zero-has-no-reciprocal")]
NaN is not an error. It is a number.
Types as values
type gives the static type of an expression as a type value. The type
is as precise as the engine can make it: the type of 3 is the literal type
3, a subtype of integer.
type(3)
// ➔ TypeFrom("3")
typeFrom makes a type value from its text, and stringFrom gives the text
of a type value. The is operator tests whether a value has a type, and
Subtype tests whether one type is a subtype of another:
(3 is integer, 3 is string)
// ➔ (true, false)
Subtype("integer", "real")
// ➔ true
Strings
A string is a sequence of characters. A character is what a reader sees
as one character (a grapheme cluster), even when Unicode encodes it with
several code points. length, characters and the other string operations
count characters. unicodeScalars, utf8 and utf16 give the encoded
integers.
characters("naïve")
// ➔ ["n", "a", "ï", "v", "e"]
Indexing a string gives a character. A character and the one-character string with the same content are the same value, so every string operation accepts a character where it accepts a string, and a dictionary accepts a character as a key. The result is the result for the one-character string:
toUpperCase("abc"[1])
// ➔ "A"
A string literal can include the value of an expression with \(…):
let n = 7
"n = \(n)"
// ➔ "n = 7"
LaTeX
Latex converts an expression to a LaTeX string, and parse converts a
LaTeX string to an expression. In an extended string literal (#"…"#), a
backslash is an ordinary character, so LaTeX commands need no escapes:
Latex(x^2 / 2)
// ➔ "\frac{x^2}{2}"
parse(#"\frac{x}{2}"#)
// ➔ 1/2 * x
Random numbers
The random functions take a domain to draw from, never a seed. To make
the draws reproducible, wrap the work in withRandomSeed, which makes every
draw inside it replay identically.
| Replacement | one draw | k draws |
|---|---|---|
| with replacement | random(xs) | randomChoice(xs, k) |
| without replacement | random(xs) | randomSample(xs, k) |
| all of them | randomShuffle(xs) |
random(xs) and randomChoice(xs, 1) have the same distribution: with a
single draw, with and without replacement coincide. randomChoice returns a
list.
The generator, the seed folding, the agreement of interpreted, compiled and GPU code, and the number of draws each function consumes are specified in the Randomness Model note.
Migrating from the previous random operators
RandomInteger, RandomList, RandomSeed, Sample and Shuffle have been
removed, along with the ce.randomSeed property of the JavaScript API and
every seed argument. Each removed name gives an operator-removed error that
names its replacement, so a stored document fails visibly rather than
silently stopping to randomize.
| Was | Now |
|---|---|
Random(seed) | withRandomSeed(seed, random()) |
Random(n), n > 0 | random(0..n-1) |
Random(m, n), m < n | random(m..n-1) |
RandomInteger(a, b) | random(a..b) |
RandomList(n) | randomChoice(interval(0, 1), n) |
RandomList(n, seed) | withRandomSeed(seed, randomChoice(interval(0, 1), n)) |
RandomSeed(s) | withRandomSeed(s, …) around the work |
Sample(xs, k) | randomSample(xs, k) |
Shuffle(xs) | randomShuffle(xs) |
Shuffle(xs, seed) | withRandomSeed(seed, randomShuffle(xs)) |
ce.randomSeed = s | withRandomSeed(s, …) |
Note the -1 of the Random(n) and Random(m, n) rows: the old upper bound
was excluded, and a range includes both ends. The rows hold only in the
stated cases. Rewrite the other old calls (n ≤ 0, m ≥ n) by hand, because
a range with reversed bounds is a descending range, not an empty one.
Functions
A function is a value: it can be an argument of a function, the result of a
function, or the value of a variable. Its type is a function signature, such
as (real, integer) -> boolean.
Function literals
A function literal is written with =>: x => 2 * x,
(x, y) => 2 * x + y. Its parameters can have a type, a default value, a
rest parameter or a tuple pattern: see
Anonymous functions and
Functions. The body can be a do block, with
locals, loops and conditionals.
function clamp(x, lo, hi) { min(max(x, lo), hi) }
[clamp(5, 0, 3), clamp(-1, 0, 3)]
// ➔ [3,0]
Compiled code calls a function only when it can see the function where the call is written (see Function values).
Shorthand function literals
A shorthand function literal is an expression whose parameters are not
listed. They are its wildcards, _, _2, …, or, when it has none, its
unknowns: the symbols that have no value.
[apply(_ * _, 3), apply(_ + _2, 1, 2), apply(x * y, 2, 3)]
// ➔ [9,3,6]
When an unknown is the parameter, make sure that the symbol has no value in the current scope. An expression with no wildcard and no unknown is a constant function:
apply(3, 5)
// ➔ 3
The unknowns of an expression become its parameters only when the
expression is known not to be a function. An expression whose type is
unknown, such as a call of a function with no definition, is kept as a
function value, and is applied once its value is known. Here g(f) is not
read as the function f => g(f), because g(f) may itself be a function:
apply(g(f), x)
// ➔ Apply(g(f), x)
let g = (a, b) => a + b
apply(g(f), x)
// ➔ f + x
Once g has a value, g(f) is g applied to its first argument, a
function of one argument. To apply a function whose result type is not
known as a shorthand, use a wildcard: map(f(_), xs) maps f over xs
whether or not f is defined.
The name of a library function is also a function value:
[map(sin, [0, pi]), apply(max, 2, 3)]
// ➔ [[0,0],3]
Anonymous functions
A function that is not bound to a name is an anonymous function. It is
often the argument of another function: map(x => 2 * x, xs), or with a
wildcard, map(_ * 2, xs). See
Anonymous functions.
Evaluating a function literal
A function literal is applied by a call, or by apply:
[(x => x + 2)(11), apply(_ + 2, 4)]
// ➔ [13,6]
Closures
A closure is a function literal that reads a variable of the scope where it is defined. It captures the binding of the variable, not its value at that time: when the function is applied, it reads the value that the binding holds then, so an assignment made after the definition is visible to the function.
let a = 10
let f = (x) => a + x
a = 20
f(1)
// ➔ 21
A variable of the same name declared in another scope is another
binding, which the function does not read. Here the function captured the
inner a:
let f = do { let a = 10; (x) => a + x }
let a = 100
f(1)
// ➔ 11
The same rule applies to a function called in the body: a call reads the function that its name denotes where the call is written (see Scoping).
Broadcasting over collections
When a function whose parameters have scalar types is applied to a finite list or range, the call is broadcast: the function is applied to each element, and the result is a list. A function with several parameters is applied element by element (zip semantics), and a scalar argument is repeated for each element.
f(x) = x^2 + 1
[f([1, 2, 3]), f(1..3)]
// ➔ [[2,5,10],[2,5,10]]
h(x, y) = x + y
[h([1, 2, 3], 10), h([1, 2, 3], [10, 20, 30])]
// ➔ [[11,12,13],[11,22,33]]
Broadcasting is decided by the evaluated argument, not by its written form: an argument that evaluates to a list, such as a call of a function that returns a list, broadcasts too.
lst(n) = [n, -n]
k(x) = 1 if x > 0 else -1
k(lst(3))
// ➔ [1,-1]
The type of an application follows the same rule: applied to a list, the
result is a list of the result type; applied to an argument that may be a
list, such as a call whose result type is not known, it is
broadcastable<R>. For a function literal, R is the type of the body,
with each parameter typed as the element that the call maps over:
f(x, y, z) = (-y, z, x)
type(f([1, 2], [3, 4], [5, 6]))
// ➔ TypeFrom("list<tuple<integer, integer, integer>>")
For a function with a declared signature, R is the declared result type.
Tuple arguments
A function whose parameter has a scalar type (a number type or
boolean) is also applied to each component of a tuple argument, as
sin((a, b)) is (sin(a), sin(b)). The result is a tuple, with one
component type for each component. A component that does not have the
parameter type is an error in its own component.
g(u: real) = 2 * u
[g((a, b)), g([(1, 2), (3, 4)])]
// ➔ [(2a, 2b),[(2, 4),(6, 8)]]
A list of tuples is mapped over the list, then over each tuple. A parameter
with no type, or of type string, takes the tuple whole:
((u) => 7)((a, b))
// ➔ 7
Compiled code gives the same tuple: an array on the javascript target,
and a vecN on the GLSL target.
Opting out
To write a function that takes a list whole instead of each element,
declare the type of its parameter as list<…> or another collection type:
len(L: list<number>) = length(L)
len([1, 2, 3])
// ➔ 3
The parameter of a function literal with no type annotation has the type
unknown, which is read as a scalar, so the function broadcasts unless its
body shows that the parameter is a collection.
The body shows it when it passes the parameter to an operator that takes a
whole collection: mean, median, variance, standardDeviation,
mode, quartiles, max, min, sum, product, gcd, lcm,
flatten, listFrom, setFrom or tupleFrom. A list argument then binds
whole. The parameter is followed through element-wise operators
(mean(v^2), sin(v)), and through a call of another function whose
parameter binds whole, also a function assigned to a local of the body. A
scalar argument gives the scalar result.
h(v) = mean(v^2)
[h([1, 2, 3]), h(2)]
// ➔ [14/3,4]
[((v) => sum(v^2))([1, 2, 3]), ((v) => max(v))([1, 2, 3])]
// ➔ [14,3]
function w(v) { let m = (t) => mean(t); m(v) }
w([1, 2, 3])
// ➔ 2
Only a use of the parameter itself counts. A local assigned from the parameter is not followed, and the function is applied to each element:
function w(v) { let u = v; mean(u) }
w([1, 2, 3])
// ➔ [1,2,3]
Declare the parameter as a collection to take the list whole. Compiled JavaScript follows the same rule.
A function that passes a collection to itself at the position of a
parameter also takes that parameter whole, and the parameter is inferred as
list<any>:
f(n, s) = s if n == 0 else f(n - 1, [1, 2])
f(1, [0])
// ➔ [1,2]
Working with strings
A string is an indexed collection of its characters. It can be counted, indexed from 1, iterated and searched with the functions of the collections library, as a list can.
[length("shop"), "abc"[2], first("abc"), last("abc")]
// ➔ [4,"b","a","c"]
A character is not the same thing as a Unicode scalar (a code point), and neither is the same thing as a byte of an encoding. A string gives all three views: the collection view is the characters, and the other two are reached with the conversions of Views of a string.
Strings are normalized to Unicode NFC when they are made. The character
é written as one scalar (U+00E9) or as two (e and U+0301 COMBINING ACUTE
ACCENT) is the same string, of length 1. The emoji 👨🚀 is one character
made of three scalars, eleven UTF-8 bytes and five UTF-16 code units.
["e\u{301}" == "é", length("e\u{301}")]
// ➔ [true,1]
length("👨🚀")
// ➔ 1
unicodeScalars("👨🚀")
// ➔ [128104,8205,128640]
utf8("👨🚀")
// ➔ [240,159,145,168,226,128,141,240,159,154,128]
utf16("👨🚀")
// ➔ [55357,56424,8205,55357,56960]
Membership is character membership, not substring search. c in s and
contains(s, c) ask whether c is one of the characters of s, as they do
for a list. "ab" is a substring of "abc", not one of its characters. A
substring is searched with the functions of
Searching for a substring, which read their
second argument as a sequence of characters.
isDigit(c) = c in "0123456789"
isDigit("7")
// ➔ true
[contains("abc", "b"), contains("abc", "ab")]
// ➔ [true,false]
containsSequence("abc", "ab")
// ➔ true
Every string is well-formed Unicode. A host string can hold an unpaired UTF-16 surrogate, on which segmentation, UTF-8 encoding and equality are not defined. Each string that enters the engine is scanned once, and each unpaired surrogate is replaced with U+FFFD REPLACEMENT CHARACTER, so every operation on a string has a result. In Epsil, an escape for a surrogate code point is an error:
unicodeScalars("\u{D800}")
// ➔ error: invalid unicode codepoint value: U+D800
The character type
A character is exactly one user-perceived character: one NFC-normalized
grapheme cluster. It is a scalar, as boolean and number are.
character and string are disjoint: a character is not a
one-character string, and a string is not a character. A character has no
elements, so a function that descends into collections stops at a character.
string is not an alias of list<character> either. The two types have the
same element type and the same iteration, and neither is a subtype of the
other. They differ because grapheme segmentation is not stable under
concatenation: joining an e and a lone combining acute accent makes the
single character é, so a list of two characters becomes a string of one.
| Type | Relationship |
|---|---|
character | character <: scalar |
string | string <: indexed_collection<character> |
string and scalar | Not a subtype: a scalar is a boolean, a character or a number |
string and list<character> | Siblings: neither matches the other |
string and character | Disjoint: neither matches the other |
To get a character, use characterFrom, or write a
string literal where a character is expected. A literal that is exactly one
grapheme cluster becomes that character, and any other literal is a type
error. Only a literal is converted: an expression of type string is not,
so write characterFrom(s).
let c: character = "a"
type(c)
// ➔ TypeFrom("character")
let d: character = "ab"
// ➔ error: Type error: The value "ab" of type "string" is not compatible with the declared type "character" in `let d: character = "ab"`
function f(c: character) { c }
let s = "a"
f(s)
// ➔ error: Type error: expected `character`, got `string` at `s` in `f(s)`
function f(c: character) { c }
let s = "a"
f(characterFrom(s))
// ➔ "a"
Equality and ordering. Two characters are equal when their NFC scalar
sequences are the same. A character is also equal to the one-character
string with the same content, which is why c == "a", "a" in "abc" and
indexOf("abc", "b") need no conversion. The two types stay disjoint.
Characters are ordered by the code points of the cluster. The order is not
locale-aware, and will not be: the identity, membership and hashing of
values must be the same on every host.
[characterFrom("a") == "a", "abc"[1] == "a", indexOf("abc", "b")]
// ➔ [true,true,2]
characterFrom("é") < characterFrom("z")
// ➔ false
A string function also accepts a character, as Strings
describes. A symbol with no declared type that is used where a string
function expects its string is inferred character | string.
Views of a string
The default view of a string is its characters. For another decomposition, ask for it:
| View | Function | Element | When to use it |
|---|---|---|---|
| Characters | characters (synonym graphemeClusters) | character | The decomposition that iteration and indexing use. Use it to freeze the segmentation into a list. Not guaranteed to be stable across Unicode versions; the slowest to compute. |
| Unicode scalars | unicodeScalars | integer code point | Stable and fast. For work on code points. Not for substring search or display. |
| UTF-8 | utf8 | integer byte | Work on an encoding: byte buffers, input and output, hashing. |
| UTF-16 | utf16 | integer code unit | Work on an encoding, with a UTF-16 host. |
| Substrings | stringSplit | string | Splitting on whitespace or on a separator. stringSplit(s, "") splits into one-character strings, not characters, with the segmentation that characters uses. |
Unicode scalars are not an encoding: one character can be several scalars, and each scalar is a different sequence of code units in each encoding.
Searching for a substring
Substring search is the search for a contiguous subsequence, and the same
four functions do it for every indexed collection:
rangeOf,
containsSequence,
startsWith and
endsWith. A string is the case where
the elements are characters.
They differ from contains and
indexOf, which search for one element:
their second argument is a sequence of elements, and both sides are compared
character by character. This is what makes them safe with grapheme clusters:
a needle cannot match across the boundary of a cluster, because whole
characters are compared.
rangeOf("x\u{301}y", "x")
// ➔ missing
rangeOf("👨👩👧", "👩")
// ➔ missing
rangeOf("e\u{301}e", "e")
// ➔ [2]
The characters of "x\u{301}y" are x́ and y, and x is not x́ (U+0301
after x has no precomposed NFC form). "👨👩👧" is one character, a family
joined with zero-width joiners. In "e\u{301}e" the first e is part of
the character é, so the match is at index 2. A search on UTF-16 code units
would find a match in all three.
Transforming a string
A string is not changed in place: these functions return a new string.
stringReplace replaces substrings,
trim, trimStart and trimEnd remove
characters at the ends, stringRepeat repeats a string,
and padStart and padEnd pad it to a length.
Case
toUpperCase and toLowerCase map a whole
string with the Unicode default mappings, which do not depend on a locale.
For a comparison that ignores case, compare the results of
caseFold.
Strings stay whole under broadcast and flattening
A string is one value for the functions that spread over a collection:
- Broadcast. A function that broadcasts over a collection gets a string
whole, not its characters. Otherwise every such function,
Stringincluded, would map over the characters, and a function with a scalar parameter would be mapped instead of applied. flatten. A function that descends into nested collections stops at a string.
String("ab", 1)
// ➔ "ab1"
String("x", [1, 2])
// ➔ ["x1","x2"]
[flatten(["ab", "cd"]), flatten("ab")]
// ➔ [["ab","cd"],["ab"]]
Which operations return a string
Whether a collection function returns a string or a list for a string
follows from what the function does:
-
A function whose result is a part or a reordering of the characters of its argument returns a string:
reverse,rest,most,take,drop,slice,unique,sort,rotateLeft,rotateRight,filter,takeWhile,dropWhile,dedup,deleteAt,randomShuffle,randomSample.[deleteAt("abcdef", 2), reverse("abc"), sort("banana")]// ➔ ["acdef","cba","aaabnn"][unique("banana"), dedup("aabbbc"), filter("a1b2", c => c in "0123456789")]// ➔ ["ban","abc","12"]type(randomShuffle("abcdef"))// ➔ TypeFrom("string") -
A function whose result is a list of runs, each a stretch, a reordering or a part of the characters, returns a
list<string>:chunk,partition(all its forms),chunkBy,slidingWindow,permutations,combinations.tallyis not one of them: its first component holds the distinct elements, so they stay characters.[chunk("abcdef", 2), partition("abcdef", 2)]// ➔ [["abc","def"],["ab","cd","ef"]][slidingWindow("abcd", 2), combinations("abc", 2)]// ➔ [["ab","bc","cd"],["ab","ac","bc"]]tally("banana")// ➔ (["b","a","n"], [1,3,2]) -
map,flatMap,scanandzipreturn a list, even when the function returns characters. Join the result withStringorstringJoin.map(c => toUpperCase(c), "abc")// ➔ ["A","B","C"]String(map(c => toUpperCase(c), "abc"))// ➔ "ABC" -
A function whose result is not a collection of the same kind (
length,isEmpty,contains,count,any,all,indexOf,at,first,last,position,find,reduce,fold) does on a string what it does on any indexed collection. In LaTeX,|s|of a string is itscount, and thecountof a string is serialized as|s|.let n = parse(#"|\text{abc}|"#)n// ➔ 3Latex(parse(#"|\text{abc}|"#))// ➔ "\vert\text{abc}\vert" -
A set function reads a string argument as its characters.
setMinusis the exception: its other arguments are the values to remove, sosetMinus(S, "ab")removes the string"ab"fromS, not the charactersaandb.union(set(1), "ab")// ➔ Set(1, "b", "a")setMinus(set(1, "ab"), "ab")// ➔ Set(1) -
A numeric function (
sum,product,mean,max,gcd, …) does not read a string as its characters. A character is not a number, so the result is an error or stays unevaluated, never a wrong number.sum("abc")// ➔ error: Runtime error: expected `number`, got `character`max("abc")// ➔ max("abc")
The re-segmentation caveat
A function that returns a string splits it into characters, works on the characters, then joins them and splits the result again. The join can merge two characters into one, so the result can have fewer characters than the argument. This follows from grapheme segmentation:
String(characters(s)) == s, always.characters(String(cs))can have fewer elements thancs: the charactereand a lone combining acute accent, each a character, join into the one characteré.- So
reversecan change the number of characters: a combining mark that followed one character can end up after another one.
String(characters("héllo")) == "héllo"
// ➔ true
[length(["e", "\u{301}"]), length(String(["e", "\u{301}"]))]
// ➔ [2,1]
characters(reverse("\u{301}a"))
// ➔ ["á"]
To keep a segmentation that later operations cannot change, take it as a
list with characters.
Unicode-version stability
The boundaries of grapheme clusters are defined by Unicode Standard Annex #29, and can change when the Unicode data of the host (ICU) is updated:
- The number of characters of an unusual cluster can differ between hosts. A test that checks such a count should name the Unicode version it assumes.
- A literal is converted to a
characterby the same segmentation, so an ICU update that changes the cluster count of a literal changes whether the program type-checks.
Unicode scalars and their UTF-8, UTF-16 and UTF-32 encodings are fixed and stable. Only the character view can change.
Compiling string operations
A string operation that cannot be compiled to a target with the same character counts fails to compile, with a diagnostic, rather than counting code units: see Compiling.
Annotated expressions
An annotated expression carries metadata that does not change what the
expression means: the color or size of its text, a tooltip, a link. It can
annotate a string, and also a variable, an operator or a function, for
instance to highlight part of a formula. In LaTeX, \textcolor makes an
annotated expression: \textcolor{blue}{\pi} is
["Annotated", "Pi", {"dict": {"color": "blue"}}]. Annotated expressions are
like the attributed strings of other systems. See Annotated.
An annotated expression evaluates to the expression without its metadata, and
parse evaluates what it reads, so parse(#"\textcolor{blue}{\pi}"#) is
pi. A held annotated expression keeps its metadata, and its LaTeX applies
it:
parse(#"\textcolor{blue}{\pi}"#)
// ➔ pi
Latex(Hold(Annotated(pi, {"color" -> "blue"})))
// ➔ "\mathrm{Hold}(\textcolor{blue}{\pi})"
When \textcolor (or \color) wraps an operator alone, such as = in
x \textcolor{red}{=} y, the operator is parsed as usual and the color is
dropped: an annotation cannot be attached to an operator alone. A colored
operand, such as \textcolor{red}{x + 1}, is still annotated.
parse(#"x \textcolor{red}{=} y"#)
// ➔ x == y
Text expressions
A Text expression is a sequence of strings, annotated expressions and other
Text expressions: formatted text, such as the result of parsing
\text{Hello \textbf{world}}. In LaTeX, the elements of a held Text
expression are serialized one by one, each with the commands of its
formatting.
Latex(Hold(Text("Hello ", Annotated("world", {"color" -> "blue"}))))
// ➔ "\mathrm{Hold}(\text{Hello }\textcolor{blue}{\text{world}})"
A String converts each of its arguments to text and joins them, so the
formatting of an annotated argument is lost. Evaluating a Text expression
gives the same plain string:
String("Hello ", Annotated("world", {"color" -> "blue"}))
// ➔ "Hello world"
Text("Hello ", Annotated("world", {"color" -> "blue"}))
// ➔ "Hello world"
Text and LaTeX
LatexString marks a string as a LaTeX fragment;
Latex serializes an expression to LaTeX, and parse
parses LaTeX. The functions of the collections
library apply to strings.
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.
about
(any) -> dictionary<any>
- argument 1 — The expression to describe; it is not evaluated, so a name describes its definition. Sample:
pi.
Return information about an expression as a dictionary: its kind (symbol, constant, function, number, string, expression), its static type and, when applicable, its name, value, signature, clause listing, attributes (the algebraic flags and lazy), description, examples, keywords, wikidata and url.
about(pi)
// ➔ {"name" -> "Pi", "kind" -> "constant", "type" -> "real<3.141592653589793..3.141592653589794>", "description" -> "The constant π ≈ 3.14159, the ratio of a circle's circumference to its diameter.", "examples" -> ["N(Pi)","Cos(Pi)"], "wikidata" -> "Q167"}
The dictionary has these keys, when they apply:
kind:"symbol","constant","function","multi-clause function (n clauses)","hold function (arguments are bound unevaluated)","number","string"or"expression";type: the static type, as a string, astypegives it;name: the name of a symbol;value: the value, when it differs from the expression;signature: the signature of a function;clauses: the clauses of a multi-clause function, one string each, in declaration order, with their overlap and coverage;attributes: the algebraic attributes of a function, then"lazy"when it receives its arguments unevaluated;examples,keywords,description,wikidata,url: the documentation of the definition.
The type of a numeric constant is the real type narrowed to a range around
its value, and real is a finite real.
about(pi)["type"]
// ➔ "real<3.141592653589793..3.141592653589794>"
MathJSON: About
["About", expr].
["At", ["About", "Pi"], "'type'"]
// ➔ "real<3.141592653589793..3.141592653589794>"
angle
(any+) -> number
- arguments 1, … — A point of the angle, in order; the vertex is the middle one of three. Sample:
A.
Angle mark / measure (\angle ABC, \varangle XYZ, ∠ABC) — opaque typed head; not evaluated.
angle(A, B, C)
// ➔ Angle(A, B, C)
MathJSON: Angle • LaTeX: \angle
Annotated
(expression, dictionary<any>) -> expression
Attach metadata or style annotations to an expression.
Annotated(x^2, {"color" -> "blue"})
// ➔ x^2
Annotated(expr, attributes) behaves as expr and carries metadata in the
dictionary attributes. The metadata has no effect on evaluation:
Annotated is inert and evaluates to expr. Use it to attach style or
meaning for display, such as a color, a tooltip or a highlight. See
Annotated expressions.
Annotated(1 + 1, {"color" -> "red"})
// ➔ 2
Attributes
The LaTeX serializer reads these keys:
color: a color name or a hex code, written with\textcolor.backgroundColor: a color name or a hex code, written with\colorbox.mathStyle:"normal"(display math),"compact"(inline math),"script"or"scriptscript".size: a number from 1 to 10, where 5 is the normal size.fontFamily:"monospace"or"sans-serif".fontWeight:"bold".fontStyle:"italic"or"normal".border:Truefor a box around the expression.
Other keys, such as tooltip, link, language, cssClass and cssId,
are kept with the expression for the application that displays it.
MathJSON: Annotated
["Annotated", expr, ["Dictionary", …]], or with a {dict: …} object as
the second argument.
["Equal",
"circumference",
["Multiply", 2, ["Annotated", "Pi", {"dict": {"color": "blue"}}], "r"]
]
In LaTeX, this is \mathrm{circumference} = 2 \cdot \textcolor{blue}{\pi} \cdot r.
apply
(name: any, arguments: any*) -> unknown
name— The function: a name or a function literal; another expression is read as a function of its free variables. Sample:sqrt.arguments— An argument; a function literal with scalar parameters maps over a list argument. Sample:16.
Apply a function to a list of arguments
apply(sqrt, 16)
// ➔ 4
The function is a function literal, a name whose value is a function, or an expression whose value is a function. An expression that is not a function is read as a shorthand function literal.
A function applied to fewer arguments than it declares is a function of the remaining ones:
((x, y) => x + y)(1)
// ➔ (_) => Apply((x, y) => x + y, 1, _)
[((x, y) => x + y)(1)(2), apply(apply((x, y) => x + y, 1), 2)]
// ➔ [3,3]
A function applied to more arguments than it declares is an
unexpected-argument error:
((x) => x)(1, 2)
// ➔ error: Runtime error: unexpected argument
Compiled code does not build a function value: a partial application or a curried call does not compile, and the interpreter evaluates it instead (see Function values).
MathJSON: Apply • LaTeX: apply
["Apply", function, arg1, …]. An expression with a compound head,
[["g", "f"], "x"], is the same application as
["Apply", ["g", "f"], "x"].
["Apply", ["Multiply", "_", "_"], 3]
// ➔ 9
["Apply", ["Function", ["Multiply", "x", "x"], "x"], 3]
// ➔ 9
["Apply", "Power", 2, 3]
// ➔ 8
["Apply", ["Apply", ["Function", ["Add", "x", "y"], "x", "y"], 1], 2]
// ➔ 3
In LaTeX, \lhd and \rhd apply a function to one argument on the left
or on the right: f\lhd g \lhd x and x \rhd g \rhd f are both
["f", ["g", "x"]]. \rhd is the pipeline operator.
A function operand that is a subscript on the index of a sum or a product
is read as the name of a term: \sum_{k=1}^{2} f_k(x) is
["Sum", ["Apply", ["Subscript", "f", "k"], "x"], ["Limits", "k", 1, 2]],
which evaluates to f_1(x) + f_2(x). Each term is read as the term written
alone: f_1(x) is a call when f_1 is a function or has no definition, and
a product when f_1 has a value. With w_1 = 2 and w_2 = 3:
["Sum", ["Apply", ["Subscript", "w", "i"], 4], ["Limits", "i", 1, 2]]
// ➔ 20
applyWhole
MathJSON ApplyWhole · (name: any, arguments: any*) -> unknown
name— The function: a name or a function literal. Sample:x => (x, x).arguments— An argument, bound whole: a list argument is not mapped over. Sample:[1, 2].
Apply a function to arguments, each bound whole (engine-internal).
applyWhole(x => (x, x), [1, 2])
// ➔ ([1,2], [1,2])
arbitraryConstant
(integer) -> number
- argument 1 — The index
kof the constant, a positive integer; the same index is the same value. Sample:1.
ArbitraryConstant(k): an arbitrary number, the k-th of a result: a constant of integration, the free parameter of an identity. Inside one result, two calls with the same index are the same value, and two calls with different indexes are independent. It has no value.
arbitraryConstant(1) - arbitraryConstant(1)
// ➔ 0
arbitraryConstant(k) is any number, such as a constant of integration, and
arbitraryInteger(k) any integer, such as the parameter of a family of
solutions, in a result of solve, dsolve or rsolve. In one result, two
calls with the same index are the same value, and two calls with different
indexes are independent. A call has no value: it is not an unknown, it is not
declared in any scope, and an expression that holds one does not compile.
[arbitraryConstant(1) - arbitraryConstant(1), arbitraryConstant(1) == arbitraryConstant(2)]
// ➔ [0,ArbitraryConstant(1) == ArbitraryConstant(2)]
The indexes of a result start at the first index that its input does not use, so two separate results both use the index 1: renumber one before you combine them.
MathJSON: ArbitraryConstant
["ArbitraryConstant", k], ["ArbitraryInteger", k]. In LaTeX, a call is
written in the command \constant, which shows only its argument:
\constant{c_{1}} is ArbitraryConstant(1) and \constant{n_{1}} is
ArbitraryInteger(1); without it, c_1 is a symbol. A renderer that does not
know the command needs \newcommand{\constant}[1]{#1}.
["Solve", ["Equal", ["Sin", "x"], 0], "x"]
// ➔ ["List", ["Multiply", "Pi", ["ArbitraryInteger", 1]]]
arbitraryInteger
MathJSON ArbitraryInteger · (integer) -> integer
- argument 1 — The index
kof the integer, a positive integer; the same index is the same value. Sample:1.
ArbitraryInteger(k): an arbitrary integer, the k-th of a result: the parameter of a family of roots, of a diophantine or a congruence solution. Inside one result, two calls with the same index are the same value, and two calls with different indexes are independent. It has no value.
solve(sin(x) == 0, x)
// ➔ [pi * ArbitraryInteger(1)]
arc
(any+) -> number
- arguments 1, … — A point of the arc, in order. Sample:
A.
Arc / wide-hat accent measure (\widehat{ABC}) — opaque typed head; not evaluated.
arc(A, B, C)
// ➔ Arc(A, B, C)
MathJSON: Arc • LaTeX: \widehat
AssertPresent
(any) -> unknown
Assert that a value is present: return it unchanged, or an expected-present error when it is ABSENT (missing, NaN, or a point whose coordinates are all NaN). nothing is the value of an empty block, not an absent datum, and passes through; an error operand propagates. Epsil spells it x?!. Only the value itself is checked, never the cells of a collection.
[1, 2][1]?!
// ➔ 1
Assign
(expression | symbol, any) scope -> any
Assign a value to a symbol or define a sequence. The RHS is evaluated immediately and ce.assign(name, val) mutates the binding in the current scope chain. When used inside a Block, the assignment is visible to subsequent statements in the block (sequential semantics).
let x = 3
x = x + 1
x
In Epsil, x = v assigns a declared variable. The value is evaluated when
the assignment is: a symbol that has a value at that moment is replaced by
the value. An assignment keeps the type of the variable, and a value of
another type is the error assignment-type-mismatch. An assignment to a name
that is not declared is the error assignment-to-undeclared-variable.
let a = 1
let b = a
a = 2
b
// ➔ 1
let x: integer = 1
x = 2.5
// ➔ error: Static error: `x` has the type `integer`, and the value has the type `2.5` in `x := 2.5`
A function is assigned like any other value, let double = x => 2 * x, or
defined with double(x) = 2 * x (see
Functions). An assignment is not pure: it
changes the state of the engine.
let double = x => 2 * x
double(4)
// ➔ 8
MathJSON: Assign • LaTeX: \coloneq
["Assign", symbol, value]. A symbol with no value stays symbolic in the
stored value, and has its current value when the assigned symbol is
evaluated: see
When is the value captured?.
The definition is looked up in the enclosing scopes. Outside every block (an
Assign that the host evaluates, or ce.assign()), an assignment to a name
with no definition declares it, with the type of the value. In a Block, a
function body or the body of a binder, it is the error
assignment-to-undeclared-variable.
An assignment is a statement, never an operand: ["f", ["Assign", "a", 2]]
is the error assignment-in-operand. A block whose last statement is an
Assign has the value Nothing.
["Block", ["Assign", "x", 5], "x"]
// ➔ an assignment-to-undeclared-variable error
["Block", ["Declare", "x", "'unknown'", 5], "x"]
// ➔ 5
The value can be a function literal or a shorthand function literal. In
LaTeX, \operatorname{double}(x) \coloneq 2x and
\operatorname{double} \coloneq x \mapsto 2x are both:
["Assign", "double", ["Function", ["Multiply", "x", 2], "x"]]
assume
(any) scope -> string
- argument 1 — The predicate to assume, such as an inequality or a membership; another expression gives "not-a-predicate". Sample:
x > 0.
Record an assumption about a symbol. Evaluates to the outcome as a string: "ok", "tautology", "contradiction", "not-a-predicate" or "internal-error".
assume(x > 0)
The predicate is an equality, an inequality or a membership. Its symbols can be undeclared, and assuming does not declare them. Every outcome is a value: an argument that is not a predicate is not an error.
| Outcome | Meaning |
|---|---|
"ok" | the assumption was recorded |
"tautology" | the existing assumptions imply it |
"contradiction" | it conflicts with the existing assumptions |
"not-a-predicate" | the argument is not a proposition |
"internal-error" | the assumption could not be processed |
[assume(x > 0), assume(1 > 0), assume(1 < 0), assume(42)]
// ➔ ["ok","tautology","contradiction","not-a-predicate"]
assume is not a pure function: it changes the state of the engine. See
Assumptions.
MathJSON: Assume
["Assume", predicate].
["Assume", ["Element", "x", "Integers"]]
// ➔ "ok"
baseForm
(x: T, base: (number | string)?) -> T where T: number
x— The number. Sample:255.base— The base in which the number is written, 10 by default; a symbol for a symbolic base. Sample:16.
BaseForm(x, base): the number x unchanged, marked to be written in base (10 by default). In LaTeX, a numeral with a base subscript, 10111_2 or 161_b, parses to it.
baseForm(23, 2)
// ➔ 23
baseForm evaluates to the number it represents, so a number written in a
base takes part in arithmetic. The base is an integer from 2 to 36, 10 by
default.
baseForm(23, 2) + 1
// ➔ 24
baseForm(11, 2) * baseForm(5, 2)
// ➔ 55
Parsing
In LaTeX, a numeral with an integer subscript, such as 10111_2 or
2748_{16}, is parsed as BaseForm when every digit is valid in the base.
Otherwise it stays a Subscript. parse evaluates the BaseForm, which
gives its value.
parse("10111_2")
// ➔ 23
parse("19_2")
// ➔ Subscript(19, 2)
let q = parse("11_8 - 3_8 = 6_8")
q
// ➔ true
A symbol subscript, such as 161_b, is parsed as BaseForm of the
polynomial of the digits in that base, so an equation in an unknown base can
be solved:
parse("161_b")
// ➔ b^2 + 6b + 1
let e = parse("161_b + 134_b = 315_b")
solve(e, b)
// ➔ [0,8]
MathJSON: BaseForm
["BaseForm", value], ["BaseForm", value, base]. In LaTeX, BaseForm is
written value_{base}, with the digits in the base, and a digit above 9 as
a letter: ["BaseForm", 42, 16] is \mathrm{2a}_{16}.
["BaseForm", 23, 2]
// ➔ 23
Block
(unknown*) -> unknown
Evaluate a sequence of expressions in a local scope, sequentially. Each operand is evaluated in order; later operands observe side effects (Assign, Declare) of earlier operands. The block's value is the value of the last expression. Short-circuiting heads (Return, Break, Continue) terminate the sequence early.
IMPORTANT — consumers translating simultaneous action tuples (e.g. Desmos (a → 1, b → a + 1) where b reads the pre-action a) must rewrite to a snapshot-then-commit Block: bind each RHS to a fresh temp first, then assign the temps to the LHS symbols. See https://cortexjs.io/compute-engine/reference/control-structures/ for the canonical recipe.
In Epsil, a block is the { … } after if, else, for, while and
function, and do { … } in an expression. A block creates a scope: its
declarations are not visible after it.
do { let b = 2; b }
b
// ➔ b
The value of a block is the value of its last expression. When the last
statement is a declaration or an assignment, the value is nothing: end
the block with the name.
do { let b = 2; b }
// ➔ 2
When a statement of the block evaluates to a break, a continue or a
Return, the block stops there, and its value is that statement.
Scoping is lexical. A nested scope (an inner block, a branch of an if, a
loop body) reads the variables of the enclosing block, and an assignment to
a variable of an enclosing block updates it. A let in the inner block
declares a new variable, which hides the outer one in the inner block.
let a = 1
do { a = 2 }
a
// ➔ 2
let a = 1
do { let a = 2; a } + a
// ➔ 3
Declarations and assignments
A local of a block is made only by a declaration: let, const, or a
function statement. An assignment x = v writes the variable that is in
scope, and never makes one. An assignment to a name that no scope declares
is an error, at any depth of the block, in a function body, and in the body
of a binder.
do { c = 5; c * 2 }
// ➔ error: Static error: `c` is not declared: write `let c = …` in `do {c := 5; c * 2}`
let c = 1
do { c = 5; c * 2 }
// ➔ 10
A let without a value declares a local that an assignment gives its value
later. A read of the local before an assignment has run is an error when the
block runs, also when the assignment is in a branch that is not taken:
do { let x; x = 3; x * 2 }
// ➔ 6
do { let x; x }
// ➔ error: Runtime error: `x` is read before it has been given a value
do { let t; if false { t = 1 }; t }
// ➔ error: Runtime error: `t` is read before it has been given a value
A local is not read before its declaration. The initial value of a declaration reads the name outside the block:
do { y; let y = 1 }
// ➔ error: Static error: `y` is used before the statement that declares it in this block in `do {y; let y = 1}`
let z = 9
do { let z = z + 1; z }
// ➔ 10
A second declaration of a name in one block is an error.
do { let a = 1; let a = 2; a }
// ➔ error: Static error: variable redeclaration: a in `do {let a = 1; let a = 2; a}`
An assignment is a statement, never an operand: assignments do not chain.
let a = 1
a = a = 2
// ➔ error: An assignment is a statement, not a value, so assignments do not chain; write two statements, "b := 5; a := b", or "a := (b == 5)" if the comparison was meant
A later assignment keeps the type of the local: its declared type, or the type of its initial value. A number can become another number. A list loses its fixed length and keeps the type of its elements; a tuple keeps its number of components, whose types are widened. An empty list has elements of an unknown type. Another type is an error.
do { let x = 1; x = "a" }
// ➔ error: Static error: `x` has the type `number`, and the value has the type `string` in `do {let x = 1; x := "a"}`
let L = [1, 2]
L = [1, 2, 3]
L
// ➔ [1,2,3]
let L = [1, 2]
L = ["a"]
// ➔ error: Static error: `L` has the type `list<number>`, and the value has the type `list<string^1>` in `L := ["a"]`
let p = (1, 2)
p = (3, 4.5)
p
// ➔ (3, 4.5)
let p = (1, 2)
p = (1, 2, 3)
// ➔ error: Static error: `p` has the type `tuple<number, number>`, and the value has the type `tuple<integer, integer, integer>` in `p := (1, 2, 3)`
let L = []
L = ["a"]
L
// ➔ ["a"]
Local functions
A function statement in a block or in a function body declares a local
variable that holds the function, with the rules above: a call before the
statement is an error, and a second function statement or a let of the
same name is a redeclaration. The type of the local is the signature that
the statement writes, or function.
function outer() { function inner(x) { x * 3 }; inner(2) }
outer()
// ➔ 6
do { g(2); function g(x) { x + 1 } }
// ➔ error: Static error: `g` is used before the statement that declares it in this block in `do {g(2); function g(x) {x + 1}}`
type(do { function g(x: integer) -> integer { x + 1 }; g })
// ➔ TypeFrom("(x: integer) -> integer")
Translating simultaneous assignments
A block is sequential: a later assignment sees the changes made by every
earlier statement. A source language with simultaneous assignments, such as
the Desmos action (a → 1, b → a + 1), in which b reads the value of a
from before the action, cannot be translated statement by statement:
let a = 5
let b = 0
do { a = 1; b = a + 1 }
(a, b)
// ➔ (1, 2)
Evaluate every right-hand side against the old values first, into fresh locals of the block, then assign the results. The order of the assignments then does not matter, because no temporary depends on a new value.
let a = 5
let b = 0
do { let na = 1; let nb = a + 1; a = na; b = nb }
(a, b)
// ➔ (1, 6)
MathJSON: Block
["Block", expr-1, …, expr-n].
["Block", ["Declare", "b", "'unknown'", 2]]
// ➔ Nothing
["Block", ["Declare", "b", "'unknown'", 2], "b"]
// ➔ 2
["Block", ["Declare", "c", "'unknown'", 5], ["Multiply", "c", 2]]
// ➔ 10
["Block", ["Assign", "c", 5], ["Multiply", "c", 2]]
// ➔ the error assignment-to-undeclared-variable, when no "c" is declared
// outside the block. With a global "c", the block writes it, and is 10.
The error codes of the rules above are assignment-to-undeclared-variable,
read-before-declaration, variable-redeclaration,
assignment-in-operand, assignment-type-mismatch and
read-before-initialization. A ["Declare"] without a value reserves a
local that an ["Assign"] initializes later, as described under
Declare. A ["Declare"] is a statement of the block itself: one that
is directly a branch of an ["If"] or a ["Which"], the body of a
["Loop"] or a case of a ["Match"] is the error
declaration-below-statement. An assignment in an operand,
["f", ["Assign", "a", 2]] or ["Assign", "t", ["Assign", "u", 1]], is
assignment-in-operand: write
["Block", ["Declare", "a", "'unknown'", 2], ["f", "a"]]. An ["Assign"]
outside every Block and Program, one that the host evaluates, declares
the name in the current scope.
The function statement is ["DefineFunction", "g", …]. The simultaneous
assignment above, with a and b declared before the block:
["Block",
["Declare", "_next_a", "'unknown'", 1],
["Declare", "_next_b", "'unknown'", ["Add", "a", 1]],
["Assign", "a", "_next_a"],
["Assign", "b", "_next_b"]]
In LaTeX, semicolons (; or \;) separate the statements of a Block:
x \coloneq 3; x^2 + 1 parses to
["Block", ["Declare", "x", "'unknown'", 3], ["Add", ["Power", "x", 2], 1]].
The first assignment of a name is its declaration, with a value. A where
clause gives bindings to an expression:
x^2 + y^2 \keyword{where} x \coloneq 3,\; y \coloneq 4 parses to a Block that declares x and y
and ends with ["Add", ["Power", "x", 2], ["Power", "y", 2]].
BuiltinFunction
(string | symbol) -> symbol
Return a built-in function symbol by name.
BuiltinFunction("Sqrt")(16)
// ➔ 4
canonicalForm
(any, (string | symbol)*) -> any
- argument 1 — The expression, as written; with no form, its full canonical form is returned. Sample:
1 + x. - arguments 2, … — A canonical form to apply: "InvisibleOperator", "Number", "Multiply", "Add", "Power", "Divide", "Flatten" or "Order". Sample:
"Order".
Return the canonical form of an expression.
Can be used to sort arguments of an expression.
Sorting arguments of commutative functions is a weak form of canonicalization that can be useful in some cases, for example to accept "x+1" and "1+x" while rejecting "x+1" and "2x-x+1"
canonicalForm(Hold(1 + x), "Order")
// ➔ Hold(x + 1)
With no form, canonicalForm(expr) is the canonical form of the expression.
With forms, it applies only those transformations, in order, and the result
is not canonical. Comparing two partial canonical forms with isSame is a
way to accept x + 1 and 1 + x but not 2 - 1 + x.
canonicalForm(Hold(3 + 2 + 1), "Order")
// ➔ Hold(1 + 2 + 3)
MathJSON: CanonicalForm
["CanonicalForm", expr], ["CanonicalForm", expr, form1, form2, ...]. The
forms:
Order: sort the arguments of a commutative function.Flatten: flatten associative expressions, remove delimiters and spliceSequenceexpressions.Number: normalize number forms, such as["Add", 2, ["Multiply", 3, "ImaginaryUnit"]]to["Complex", 2, 3], and reduce rationals.InvisibleOperator: replace an invisible operator byMultiplyor a function application.Multiply: combine the coefficients and factors of aMultiply, and make aPowerwhen possible.Add: remove the0of anAdd, make aMultiplywhen possible, and turnSubtractandNegateintoAddandMultiply.Power: turnExp,Square,SqrtandRootintoPower.DivideappliesPowerto its operands.
["CanonicalForm", ["Add", 3, 2, 1], "Order"]
// ➔ ["Add", 1, 2, 3]
["CanonicalForm", ["Add", 1, ["Add", 2, 3]], "Flatten"]
// ➔ ["Add", 1, 2, 3]
["CanonicalForm", ["InvisibleOperator", 2, "x"], "InvisibleOperator"]
// ➔ ["Multiply", 2, "x"]
["CanonicalForm", ["Multiply", 2, 3, "x"], "Multiply"]
// ➔ ["Multiply", 6, "x"]
The canonical option of ce.parse() and ce.expr() takes the same forms.
caseFold
(character | string) -> string
- argument 1 — The text to fold. Sample:
"Straße".
CaseFold(s): a case-folded form of s, for case-insensitive comparison — caseFold(a) == caseFold(b) tests equality ignoring case. An approximation of Unicode full case folding.
caseFold("Straße")
// ➔ "strasse"
caseFold("Hello") == caseFold("HELLO")
// ➔ true
The folded form is a key for comparison, not text to display. caseFold
and toLowerCase differ where lower case depends on the context: the
lower case of "ΟΔΟΣ" ends with the final sigma ς, and its folded form
with the sigma σ, so the folded forms of both spellings are equal.
[toLowerCase("ΟΔΟΣ"), caseFold("ΟΔΟΣ")]
// ➔ ["οδος","οδοσ"]
caseFold("ΟΔΟΣ") == caseFold("οδοσ")
// ➔ true
toLowerCase("ΟΔΟΣ") == toLowerCase("οδοσ")
// ➔ false
An approximation of Unicode case folding
The host has no case-folding function, so the fold is the lower case of the
upper case, with the final sigma (U+03C2) replaced by the sigma (U+03C3).
This gives the result of Unicode full case folding for Latin, Greek and
Cyrillic text, ß and SS included. It differs for a few characters that
Unicode's CaseFolding.txt maps in a special way, among them Cherokee and
some Turkic and Lithuanian sequences.
MathJSON: CaseFold
["CaseFold", s].
["CaseFold", {str: "Straße"}]
// ➔ "strasse"
["Equal", ["CaseFold", {str: "ΟΔΟΣ"}], ["CaseFold", {str: "οδοσ"}]]
// ➔ "True"
characterFrom
(character | string) -> character
- argument 1 — The text of exactly one character (one grapheme cluster). Sample:
"é".
CharacterFrom(s): the character s denotes. s must be exactly one user-perceived character (one grapheme cluster) after NFC normalization; an empty or multi-character string is an error.
characterFrom("é")
// ➔ "é"
One character means one grapheme cluster, not one code point: a
precomposed or a decomposed é, an emoji sequence joined with zero-width
joiners and a flag each qualify. An empty string or a string of several
characters is an error, never a truncation.
characterFrom("👨👩👧")
// ➔ "👨👩👧"
characterFrom("e\u{301}") == characterFrom("é")
// ➔ true
characterFrom("ab")
// ➔ error: Type error: expected `character`, got `string` at `"ab"` in `characterFrom("ab")`
characterFrom("")
// ➔ error: Type error: expected `character`, got `string` at `""` in `characterFrom("")`
One cluster always segments to itself, so characterFrom(String(c)) == c
for every character c.
let c = characterFrom("x")
characterFrom(String(c)) == c
// ➔ true
A string literal also becomes a character where a character is expected:
see The character type.
MathJSON: CharacterFrom
["CharacterFrom", s]. MathJSON has string literals but no character
literal, so ["CharacterFrom", "'x'"] is also the form in which a character
is written: a character serializes to it, and it canonicalizes back to the
same character. A string literal converted to a character in Epsil is
written in this form too.
["CharacterFrom", {str: "x"}]
// ➔ ["CharacterFrom", "'x'"]
["Characters", {str: "abc"}]
// ➔ ["List", ["CharacterFrom", "'a'"], ["CharacterFrom", "'b'"], ["CharacterFrom", "'c'"]]
characters
(character | string) -> list<character>
- argument 1 — The text to split; an empty string gives
[]. Sample:"héllo".
Characters(s): split a string into a list of user-perceived characters (grapheme clusters). Synonym: GraphemeClusters. For stable integer decompositions see UnicodeScalars, Utf8 and Utf16. A non-string argument leaves the expression unevaluated.
characters("héllo")
// ➔ ["h","é","l","l","o"]
A grapheme cluster is the smallest unit of text that a reader sees as
one character. It can be one Unicode scalar or several. The character é
can be one scalar (U+00E9, the precomposed form of NFC) or two (e U+0065
and the combining acute accent U+0301, the decomposed form of NFD), and both
are one grapheme cluster. An emoji such as 👩🚀 or a flag such as 🇫🇷 is
one grapheme cluster of several scalars.
| String | Characters | Unicode scalars |
|---|---|---|
é (NFC) | ["é"] | [233] |
é (NFD) | ["é"] | [101, 769] before NFC normalization, [233] after |
👩🎓 | ["👩🎓"] | [128105, 8205, 127891] |
[characters("e\u{301}"), characters("🇫🇷")]
// ➔ [["é"],["🇫🇷"]]
unicodeScalars("👩🎓")
// ➔ [128105,8205,127891]
The boundaries of grapheme clusters are defined by the Unicode Standard (UAX #29) and can change as characters, scripts and emoji sequences are added. Unicode scalars and their UTF-8, UTF-16 and UTF-32 encodings are fixed across Unicode versions (see Unicode-version stability).
Iterating or indexing a string gives the same characters, so characters is
needed only for the list itself: to keep the segmentation from changing when
the characters are joined again (see
The re-segmentation caveat).
String(characters(s)) == s always holds; characters(String(cs)) can have
fewer elements than cs.
graphemeClusters is a synonym, the original name of this function.
See also characterFrom, stringSplit,
utf8, utf16 and unicodeScalars.
MathJSON: Characters
["Characters", s], and its synonym ["GraphemeClusters", s]. The elements
of the result are characters, so they are written in the CharacterFrom
form.
["Characters", {str: "ab"}]
// ➔ ["List", ["CharacterFrom", "'a'"], ["CharacterFrom", "'b'"]]
Coalesce
(any+) -> unknown
Return the first operand that is not ABSENT (missing, NaN, or a point whose coordinates are all NaN), evaluated left-to-right. If every operand is absent, the last operand’s value is returned verbatim (still absent). nothing passes through without selecting a fallback.
Coalesce(missing, NaN, 3, 4)
// ➔ 3
Colon
(any, any) -> expression
Type annotation (a : b) — opaque typed head.
MathJSON: Colon • LaTeX: :
composition
MathJSON Composition · (function*) -> function
- arguments 1, … — A step of the composition; the rightmost step is applied first, and no step gives the identity function. Sample:
sin.
The composition of functions, applied right to left: composition(f, g, h)(x) is f(g(h(x)))
composition(sin, exp)(0)
// ➔ sin(1)
composition(f, g)(x)
// ➔ f(g(x))
conforms
MathJSON Conforms · (subject: any, protocols: string+) -> boolean
subject— The value whose type is tested, or a type value to test that type. Sample:"abc".protocols— The name of a protocol; an unknown name is an error. Sample:"Copyable".
True iff the subject conforms to EVERY named protocol. A type VALUE subject asks whether that type conforms (the branch is unambiguous because the type primitive itself declares no conformances); any other subject is evaluated once and its precise type is asked. This is the lowering of the Epsil x is Hashable & Comparable test. A valueless or unresolved subject stays symbolic; an unknown protocol name is an error; an Error-valued subject answers False (the error type declares no conformances). Conformance is monotone but late-bound: the answer reflects the registry at the moment of evaluation.
protocol Copyable {}
type string is Copyable
conforms("abc", "Copyable")
Declare
(symbol, type: (string | symbol)?, value: any?, attributes: dictionary<any>?) scope -> any
Declare a symbol in the current scope, optionally assigning a type and an initial value. An optional trailing attributes dictionary (with keys type, value, constant and holdUntil) can further describe the definition, e.g. to declare a constant. Another key in that dictionary is the error invalid-declaration-attribute: a dictionary given as the initial value is the value attribute, or is followed by an attributes dictionary. With a value, evaluates to that value; otherwise evaluates to nothing.
let x: integer = 5
x + 1
In Epsil, let x = v declares a variable and const c = v a constant:
Declarations gives the rules. A let without a value,
let x or let x: integer, declares a variable that is given its value
later by an assignment. Its type is the annotation. Without one, the type is
inferred from a single later assignment in the same sequence of statements,
before any use, that is not in a branch or a loop and calls no function:
after let x; x = 1, x is a number. Otherwise the type is unknown. A
read of the variable before it has a value is an error when the program
runs. A second declaration of a name that the program or the block already
declares is an error, also at the top level of a program. A constant cannot
be assigned.
let x: integer
x = 4
x + 1
// ➔ 5
let x: integer
x = 2.5
// ➔ error: Static error: `x` has the type `integer`, and the value has the type `2.5` in `x := 2.5`
let x
x
// ➔ error: Runtime error: `x` is read before it has been given a value
const c = 299792458
c = 3
// ➔ error: Static error: cannot assign a value to the constant `c` in `c := 3`
MathJSON: Declare
["Declare", symbol, type, value], ["Declare", symbol, attributes]. A
standalone Declare with a value evaluates to that value; in a Block, a
Declare is a statement, and a block whose last statement is a Declare has
the value Nothing.
In a Program or a Block, a Declare with no value reserves a variable
that is initialized later. An explicit type fixes its type. Otherwise the
type is inferred from a single later initialization in the same sequence of
statements, before any use; the inference does not search branches, loops or
calls, and stops at a function application (let x; x = 1 infers number,
let x; x = 1 + 2 keeps unknown). A read before the initialization is the
error read-before-initialization. Outside these sequences, a Declare
without a value is the error declaration-without-value.
In a Block, a local is made only by a Declare, which must be a statement
of the block itself: in a branch of an If, in a loop body or in a case of a
Match, it is the error declaration-below-statement. A second Declare of
a name that the block declares is the error variable-redeclaration; at the
top level, a second Declare replaces the definition. A local cannot be read
before its declaration (read-before-declaration).
The attributes dictionary has the keys type, value, constant (True
for a constant) and holdUntil ("never", "evaluate" or "N": when the
value is substituted during evaluation, as for Pi). A positional type or
value takes precedence over the same key.
["Declare", "c", "integer", 299792458, ["Dictionary", ["KeyValuePair", "constant", "True"]]]
Declare is not a pure function: it changes the state of the engine. In
JavaScript, see ce.declare().
DeclareConformance
(target: string | symbol, protocols: any, whereClauseOrImplementation: any?, implementation: dictionary<any>?) scope -> nothing
Declare that a type CONFORMS to one or more protocols — the lowering of the Epsil type string is Hashable & Comparable statement. The target rides as a type-expression string and must be named and ground (not a union, an anonymous structural type or a type alias name); the protocols ride as a List of names. An optional trailing dictionary carries the implementation block, member name -> function literal (property handlers under the mangled keys __get__x / __set__x); it may only accompany a SINGLE protocol. A CONDITIONAL conformance carries, ahead of that block, the source text of its trailing where clause as a string: the target is then a head pattern naming the variables the clause binds (list<T> with "where T is Comparable"). Conformance is monotone — it can be added but never removed — and a re-declaration is a no-op. Evaluates to nothing.
protocol Copyable {}
type string is Copyable
"abc" is Copyable
DeclareProtocol
(string | symbol, members: dictionary<any>?, parents: any?, attributes: dictionary<any>?) scope -> nothing
Declare a PROTOCOL: a set of function and property requirements a type may declare itself to satisfy. Protocols are engine-global (not lexically scoped) and are NOT types, so this is only valid at the top level of a program. The name is a symbol (or a string); the optional members ride as a dictionary of member -> ["Pair", "function"|"readonly"|"readwrite", signature], with the signature as a type-expression string. A function member's first parameter must be typed Self, the substitution token standing for the conforming type. A protocol with no members is a SEMANTIC protocol (a marker). An optional third operand ["List", parent, …] names the protocols this one EXTENDS: a type that conforms to it conforms to each of them, and its implementation block may implement their members. The members operand is then required (["Dictionary"] when there are none). An optional fourth operand documents the protocol: ["Dictionary", description: string, members: ["Dictionary", member: string]] (the /// comments of an Epsil protocol statement); the two operands before it are then required. Evaluates to nothing.
protocol Area { function area(self: Self) -> number }
type square = tuple<side: number> is Area {
function area(self: square) -> number { self.side^2 }
}
area(square(3))
DeclareSumType
(string | symbol, any*) scope -> nothing
Declare a SUM TYPE: N nominal variants plus the transparent union that names them, in one statement — the lowering of the Epsil sugar type node = lit(num: number) | plus(op1: node, op2: node). The name is a symbol (or a string); each variant is a ["Tuple", name, payload] pair whose payload is a type string ("nothing" for a nullary variant). An optional attributes dictionary at operand 1 — ahead of the variants — carries typeParams -> "T" for a generic sum, whose parameters are distributed to each variant by usage. The sum name is forward-registered before the variants are declared, so a payload may name it bare. A variant name that already names a type, is reserved, or is a builtin is rejected and NOTHING is declared. Types are engine-global, so this is only valid at the top level of a program. Evaluates to nothing.
type shape = circle(r: number) | square(s: number)
match square(3) {
circle(r) => pi * r^2
square(s) => s^2
}
DeclareType
(string | symbol, type: string | symbol | type, attributes: dictionary<any>?) scope -> nothing
Declare a type. Types are engine-global (not lexically scoped), so this is only valid at the top level of a program — inside a block or function body it is an error. The name is a symbol (or a string) and the type a string holding a type expression, e.g. "tuple<x: integer, y: integer>". The type is nominal by default; an optional trailing attributes dictionary with alias -> True makes it a structural alias instead, and an additional typeParams -> "T, U: number" entry makes it a GENERIC alias whose uses must be applied (Pair<integer>). The declaration also mints a value constructor of the same name — ["point", 1, 2], an inert tagged value for a nominal type, a checked identity for an alias — except for a record body, which mints none. Evaluates to nothing.
type point = tuple<x: number, y: number>
point(1, 2)
In Epsil, type name = definition declares a nominal type, and
type alias name = definition a structural alias: see
Declaring a type. A value is compatible
with a nominal type only when its type is that type; any value that matches
the definition is compatible with an alias.
A type declaration also declares a constructor, a function of the same name. A tuple definition gives one argument per element; another definition gives one argument; a record definition gives no constructor, because the order of its fields is not meaningful. A nominal constructor is inert: the call is the value, and its type is the declared type. An alias constructor checks its arguments and gives the plain value.
type point = tuple<x: number, y: number>
type(point(1, 2))
// ➔ TypeFrom("point")
type alias pair = tuple<number, number>
pair(1, 2)
// ➔ (1, 2)
Types are global to the engine, so a type declaration is valid only at the top level of a program. A declaration of a name that already has a value or an operator registers nothing and is an error; a library name is shadowed. Running a program again replaces its own type declarations.
function f() { type t = integer; 1 }
// ➔ error: The type "t" is declared inside a block: types are global, so type declarations are only allowed at the top level of a program
MathJSON: DeclareType
["DeclareType", name, type], ["DeclareType", name, type, attributes],
with the type as a string. The attribute alias set to True declares a
structural alias. The declaration takes effect when the expression is
canonicalized, so later statements can use the type, and it evaluates to
Nothing. The mint option of ce.declareType() has no attribute: this
operator always declares a constructor.
["DeclareType", "point", "'tuple<number, number>'", ["Dictionary", ["KeyValuePair", "alias", "True"]]]
DefineFunction
(symbol, function, dictionary<any>?) scope -> nothing
Define one clause of a (possibly multi-clause) function: DefineFunction(f, Function(body, params…)). Unlike Assign — which replaces the binding wholesale — DefineFunction ACCUMULATES: a clause with the same parameter domain replaces the earlier clause in place, any other clause is appended, and calls dispatch to the most specific clause admitting the arguments.
fact(0) = 1
fact(n) = n * fact(n - 1)
fact(5)
Delimiter
(any, string?) -> any
Group expressions with explicit delimiters.
Delimiter(1 + 2)
// ➔ 3
Delimiter is inert: Delimiter(expr) evaluates to expr. It holds the
delimiters and separators with which expr is displayed. expr is a
function expression, usually a Sequence, not a symbol or a number.
The optional second argument is a string:
- One character: the separator.
- Two characters: the opening and the closing delimiters.
- Three characters: the opening delimiter, the separator and the closing delimiter.
The opening and closing delimiters are each one of the characters
()[]{}<>|‖⌈⌉⌊⌋⌜⌝⌞⌟⎰⎱", and do not have to match: ")]" is a valid pair. A
. as a delimiter means no delimiter. The separator is one of ,;.&:|-,
U+00B7 MIDDLE DOT, U+2022 BULLET or U+2026 HORIZONTAL ELLIPSIS.
With no second argument, the delimiters depend on expr: (,) for a
Sequence, a tuple, Single, Pair or Triple, [,] for a list and
{,} for a set.
MathJSON: Delimiter
["Delimiter", expr], ["Delimiter", expr, delim]. In LaTeX, expr is
written between the delimiters, with the separator between its elements:
["Delimiter", ["Sequence", 1, 2, 3], "'{;}'"] is
\lbrace1;2;3\rbrace. The angle brackets <> and ⟨⟩ are written
\langle and \rangle, and ‖, ⌈⌉ and ⌊⌋ as \Vert, \lceil \rceil
and \lfloor \rfloor. Square brackets are written as parentheses:
["Delimiter", ["Sequence", 1, 2, 3], "'[,]'"] is (1,2,3), because a group
in square brackets is read back as a List, not as the sequence.
digitsFrom
(s: character | string, base: (character | integer | string)?) -> integer
s— The digits, with an optional sign; with a base, a digit not valid in it is an error; without one, the longest prefix of decimal digits is read (a 0x or 0b prefix is accepted), and text with none givesNaN. Sample:"ff".base— The base, from 2 to 36, 10 by default; a numeric string is read as a number. Sample:16.
Return an integer representation of the string s in base base.
digitsFrom("ff", 16)
// ➔ 255
digitsFrom("1010", 2)
// ➔ 10
The base is from 2 to 36, 10 by default. Whitespace before and after the
digits is ignored, and a sign is read, also before a prefix. With no base,
a 0x or 0b prefix selects base 16 or 2. With a base, a prefix is read
only when it is the prefix of that base: in base 10, 0b101 is an
unexpected-digit error, and in base 16, 0b1 is the hexadecimal number
b1. An integer greater than 2^{53} stays exact.
[digitsFrom(" -42 "), digitsFrom("0xff"), digitsFrom("-0x1F"), digitsFrom("0b101", 2)]
// ➔ [-42,255,-31,5]
[digitsFrom("0b1", 16), digitsFrom("0x1F", 16)]
// ➔ [177,31]
digitsFrom("0b101", 10)
// ➔ error: Runtime error: unexpected digit: b at `b101`
digitsFrom("z", 36)
// ➔ 35
digitsFrom("123456789012345678901234567890")
// ➔ 123456789012345678901234567890
A digit that is not valid in the base is an unexpected-digit error, and a
base outside 2 to 36 an unexpected-base error.
digitsFrom("12", 2)
// ➔ error: Runtime error: unexpected digit: 2 at `2`
digitsFrom("12", 37)
// ➔ error: Runtime error: unexpected base: 37 at `37`
See also integerString, baseForm and
numberFrom.
MathJSON: DigitsFrom
["DigitsFrom", s], ["DigitsFrom", s, base].
["DigitsFrom", {str: "-42"}]
// ➔ -42
["DigitsFrom", {str: "0xff"}]
// ➔ 255
error
(expression<ErrorCode> | string, expression?) -> nothing
- argument 1 — The nature of the error: a code string, or an
ErrorCodeexpression with arguments. Sample:"oops". - argument 2 — The context of the error, such as the expression where it occurs. Sample:
x + 1.
Represent an error expression.
[1, RuntimeError("zero")]
// ➔ [1,Error("zero")]
An error is a value. When an argument of a function is an error, the result is that error. See Errors for the error codes, and the evaluation guide for the rules.
MathJSON: Error
["Error", code, context], where code is a string or an ["ErrorCode"]
expression, and context is optional.
An error that propagated out of the expression where it was raised carries a
breadcrumb of the operators it passed through: an ["ErrorTrace"] that is
always the last operand of the Error. Each frame is
["ErrorFrame", operator, index], where index is the position of the
operand the error came from, starting at 1. The frames read innermost first.
An error that did not propagate has no breadcrumb. So the breadcrumb is found
by its head, not by its position: code that reads the second operand as the
context must skip an ErrorTrace there. toString() and the LaTeX
serializer show a traced error like an untraced one.
["Add", ["Ln", "'a'"], 2]
// ➔ ["Error",
// ["ErrorCode", "'incompatible-type'", "'number'", "'string'"],
// "'a'",
// ["ErrorTrace", ["ErrorFrame", "'Ln'", 1], ["ErrorFrame", "'Add'", 1]]]
ErrorCode
(string, any*) -> error
Structured error code with optional arguments.
[1, RuntimeError(ErrorCode("out-of-range", 5))]
// ➔ [1,Error(ErrorCode("out-of-range", 5))]
evaluate
(any) -> unknown
- argument 1 — The expression to evaluate. Sample:
x + x.
Evaluate an expression.
evaluate(x + x)
// ➔ 2x
evaluate computes exactly; N gives a numeric approximation. A Hold
stays held: use ReleaseHold.
[evaluate(Hold(1 + 1)), ReleaseHold(Hold(1 + 1))]
// ➔ [Hold(1 + 1),2]
See Exact and numeric evaluation.
MathJSON: Evaluate
["Evaluate", expr].
evaluateAt
(f: function, lower: expression, upper: expression?) -> unknown
f— The function, or an expression of its free variables. Sample:x => x^2.lower— The lower bound; withoutupper, the point at whichfis evaluated. Sample:1.upper— The upper bound: the result isf(upper) - f(lower). Sample:3.
Evaluate a function at one point or between two bounds.
evaluateAt(x => x^2, 1, 3)
// ➔ 8
The function is applied as apply applies it: a function literal, a name
whose value is a function, or an expression, which is read as a shorthand
function literal of its free variables. A point that is a tuple, with one
coordinate for each parameter, gives the value at that point of a function
of several variables. A point is never a partial application: with fewer
points than the function requires, the expression stays as written.
evaluateAt(x => x^3 / 3, 0, 1)
// ➔ 1/3
evaluateAt((x, y) => x * y, (1, 2))
// ➔ 2
evaluateAt((x, y) => x * y, 1)
// ➔ ((x, y) => x * y)|_(1)
When the expression has several free variables, the point or the bounds are
for x. Write a function literal to name another variable:
[evaluateAt(k * x, 2, 5), evaluateAt(t => k * t, 2, 5)]
// ➔ [3k,3k]
The value of a derivative at a point is the derivative evaluated there. The
value of a series at a point keeps its BigO remainder, also under N:
apply normal to the series to drop it. A value with no closed form stays
an unevaluated evaluateAt.
evaluateAt(x => D(x^2, x), 3)
// ➔ 6
evaluateAt(x => series(sin(x), x, 0), 1)
// ➔ 101/120 + BigO(1)
MathJSON: EvaluateAt • LaTeX: ., |
["EvaluateAt", function, point], ["EvaluateAt", function, lower, upper].
["EvaluateAt", ["Function", ["Power", "x", 2], "x"], 3]
// ➔ 9
["EvaluateAt", ["Function", ["Divide", ["Power", "x", 3], 3], "x"], 0, 1]
// ➔ ["Rational", 1, 3]
In LaTeX, \left.\left(x^2\right)\right|_{x=3} is the value at 3, and
\left.\left(\frac{x^3}{3}\right)\right|_{x=0}^{1} the difference between
two bounds. \left.\left(xy\right)\right|_{x=1, y=2} is
["EvaluateAt", ["Function", ["Multiply", "x", "y"], "x", "y"], ["Tuple", 1, 2]].
When the bracket does not name the variable, it is x:
\left.kx\right|_{2}^{5} is 3k; write
\left.\left(kt\right)\right|_{t=2}^{5} for another variable.
The variable of a derivative, of a series or of an indefinite integral is
free in its result, so substituting a value for that variable gives an
EvaluateAt: ["D", ["Power", "x", 2], "x"] with x replaced by 3 is
["EvaluateAt", ["Function", ["D", ["Power", "x", 2], "x"], "x"], 3],
which evaluates to 6.
findRoot
MathJSON FindRoot · (equations: any, params: any, options: dictionary?) -> dictionary
equations— An equation, a residual expression read as= 0, or a list of either. Sample:x^2 - 2.params— The list of parameter specs: a symbol,(a, a0)with a start value, or(a, a0, lo, hi)with bounds. Sample:[(x, 1)].options— The options of the search; an unknown key is an error. Sample:{global -> {x -> [0, 2]}}.global(dictionary<list<real>>) — The parameters (at most two) to search over a range[lo, hi]or[lo, hi, step]for the lowest sum of squared residuals. Sample:{x -> [0, 2]}.
FindRoot(equations, params): numerically find parameter values that zero the residuals. equations is an equation (lhs == rhs), a bare residual expression (read as = 0), or a list of either. params is a list of specs (a bare symbol, (a, a0), or (a, a0, lo, hi) with box constraints), matching findFit. Returns a record {parameters, converged, stationary, residualNorm, iterations}.
converged is true only at a root: every residual is within the engine's tolerance scaled by its own equation, |r_i| ≤ tolerance · (1 + Σ_j |J_ij| · max(1, |θ_j|)), with J the Jacobian and θ the parameters, so a minimum of the sum of squared residuals that is not a root (a^2 + 1 = 0) is converged: False.
When the residual is above tolerance, the residual itself must confirm the Jacobian term: with each parameter moved by ±2 · tolerance · max(1, |θ_j|) toward and away from the zero, the change of the residual is the change the Jacobian predicts to within half, and the residual reaches tolerance, changes sign, or touches 0 to within the rounding of the parameters. So a steep equation with no root (2 - sin(10^18 a) = 0) is not converged either.
stationary is the solver's own stop test, true at such a minimum too; a stacked system of data rows next to an equation reads it as findFit reads converged. An optional third argument is the options dictionary of findFit: {global: {b: [lo, hi]}} searches the named parameters (at most two) over the range for the lowest sum of squared residuals of the whole system; the constant phase coefficients of the equations (3.22 in cos(3.22 b + c)) space the grid as the span of a variable does for a fit. With a kernel pool on the engine (ce.workers), evaluateAsync() scans the grid on the workers.
findRoot(x^2 - 2, [(x, 1)])
// ➔ {"parameters" -> {"x" -> 1.4142135624638652}, "converged" -> true, "residualNorm" -> 2.567368539985182e-10, "iterations" -> 4, "stationary" -> true}
Function
(expression, (function | symbol)*) -> function
Function(body, param1, param2, …): a function literal.
A parameter is a symbol, Typed(symbol, type), a rest parameter Spread(symbol) (last), a destructuring pattern Tuple(…), or a parameter with a default value Optional(param, default), where param is a symbol or Typed(symbol, type) and default is a number, a string, True, False, a symbol, List() or Dictionary(). The parameters with a default come after the required ones. A call that supplies the required parameters is a full call: each parameter it leaves out receives its default.
(x => x^2 + 1)(3)
// ➔ 10
((x, k = 2) => x * k)(3)
// ➔ 6
Typed parameters
A parameter with a type makes the literal a function with a named signature, and the arguments are checked against the types when the function is applied.
type((x: integer) => x + 1)
// ➔ TypeFrom("(x: integer) -> integer")
((x: integer) => x + 1)(2.5)
// ➔ error: Type error: expected `integer`, got `2.5` at `2.5` in `apply((x: integer) => x + 1, 2.5)`
An argument with no value, whose type does not show that it fits, leaves the application unevaluated, and a later evaluation checks the value. At a parameter that admits every real number, the body is applied to a symbol with no declared type.
((x: integer) => x + 1)(m)
// ➔ Apply((x) => x + 1, m)
((x: real) => x^2)(y)
// ➔ y^2
missing at a parameter of a number type or a point type gives missing,
and the body does not run. A default value does not change this: a default
fills only an argument that the call leaves out. A NaN at a numeric
parameter, and a point of NaN coordinates at a point parameter, are
accepted: the body runs with them.
map((x: integer) => x > 0, [1, missing])
// ➔ [true,missing]
((x: integer) => x + 1)(NaN)
// ➔ NaN
Return type
A return type sets the result type of the signature. When the function is
applied, a concrete result (a number, a string, a character, a boolean, or
a list or tuple of these) is checked against it. A symbolic value,
missing, nothing, NaN and an error value pass unchanged, and a real
float passes under integer or rational, so N of such a function gives
the float. Compiled code does not make this check.
function g(n: integer) -> integer { n / 2 }
g(5)
// ➔ error: Runtime error: expected `integer`, got `rational<2.5..2.5>` at `5 / 2`
function g(n: integer) -> integer { n / 2 }
N(g(5))
// ➔ 2.5
A literal assigned to a name declared with a signature takes the declared result as its return type, and is refused when the type of its body has no value in common with that result (see Typed function literals).
Generic literals
A signature with a where clause makes the literal generic (see
Generic functions). A parameter whose type
names a type variable is checked against the bound of the variable, and
each application solves the variables from the arguments:
let f: (T) -> T where T: number = (x) => x + x
f(21)
// ➔ 42
A where clause on the annotation of one parameter is not accepted: type
variables are introduced only by a clause on the whole signature.
MathJSON: Function • LaTeX: \mapsto
["Function", body, param1, param2, …]. Function is lazy: neither the
body nor the parameters are evaluated until the function is applied. In
LaTeX, x \mapsto 2x is ["Function", ["Multiply", "x", 2], "x"], and
(x, y) \mapsto 2x + y is
["Function", ["Add", ["Multiply", "x", 2], "y"], "x", "y"].
A typed parameter is ["Typed", symbol, type], with the type a string
("'integer'") or a type-name symbol, which is normalized to a string.
["Function", ["Add", "x", 1], ["Typed", "x", "'integer'"]]
["Apply", ["Function", ["Add", "x", 1], ["Typed", "x", "'integer'"]], "m"]
// ➔ ["Apply", ["Function", ["Block", ["Add", "x", 1]], ["Typed", "x", "'integer'"]], "m"]
A parameter with a default value is ["Optional", parameter, default], and
a tuple pattern is a ["Tuple", …] of parameter names, _ to skip a
position, or nested patterns. A tuple pattern is one parameter:
["Apply",
["Function", ["Multiply", "k", "x"], "x",
["Optional", ["Typed", "k", "'number'"], 2]],
3]
// ➔ 6
["Map",
["Function", ["Add", "p", "q"], ["Tuple", "p", "q"]],
["List", ["Tuple", 1, 2], ["Tuple", 3, 4]]]
// materializes to ["List", 3, 7]
A default that names a variable, such as ["Optional", "k", "n"] with n
a variable, is the error expected-a-literal-default. The form
["Typed", "k", "'number?'"] is not accepted for a parameter: it is the
error invalid-parameter-annotation.
A return type is a Typed around the body. Canonicalization moves it inside
the body Block, around its last statement:
["Function", ["Typed", ["Add", "x", 1], "'integer'"], ["Typed", "x", "'integer'"]]
// canonical form:
["Function",
["Block", ["Typed", ["Add", "x", 1], "'integer'"]],
["Typed", "x", "'integer'"]]
A generic signature can be written as a signature string in place of the
parameter list, or as a whole-signature Typed on the body, which is the
canonical form. A parameter whose type names a type variable is erased to a
bare symbol; a ground one keeps its annotation.
["Function", ["Add", "x", "x"], "'(x: T) -> T where T: number'"]
["Function",
["Block", ["Typed", ["Add", "x", "x"], "'(x: T) -> T where T: number'"]],
"x"]
In LaTeX, a parameter with no type followed by a parenthesized argument is
a call of the parameter, so a function can take a function as argument:
(g \mapsto \int_0^1 g(x)\,dx)(t \mapsto t^2) is 1/3. The exception is an
argument that contains the parameter: q \mapsto q(2q) is the product
2q^2. A parameter with a number type is a value, and the juxtaposition is
a product: ((x\colon \mathrm{real}) \mapsto x(2))(3) is 6.
A literal with a tuple pattern, a rest parameter (["Spread", name]) or a
default value has no \mapsto notation: (x, y) \mapsto xy is a function
of two parameters, not of one pair. Its LaTeX is \mathrm{Function}(…) with
its MathJSON operands, which parses back to the same literal:
\mathrm{Function}(xy, \mathrm{Tuple}(x, y)). The other type annotations
are dropped in LaTeX. Wildcards in LaTeX are \_ and \operatorname{\_2}:
\_ + \operatorname{\_2} is ["Add", "_", "_2"].
graphemeClusters
MathJSON GraphemeClusters · (character | string) -> list<character>
- argument 1 — The text to split; an empty string gives
[]. Sample:"héllo".
A collection of grapheme clusters from a string. Synonym of Characters.
graphemeClusters("héllo")
// ➔ ["h","é","l","l","o"]
head
(any) -> symbol
- argument 1 — The expression; a number gives its kind (
Integer,Real,Rational, …), a symbolSymbol. Sample:x^2.
Return the head of an expression, the name of the operator
head(x^2)
// ➔ Power
A symbol is read through its value: with x assigned a + 1, head(x) is
"Add". A symbol with no value has the head "Symbol".
let x = a + 1
[head(x), head(y)]
// ➔ [Add,symbol]
MathJSON: Head
["Head", expr].
["Head", ["Add", 2, 3]]
// ➔ "Add"
Hold
(any) -> unknown
Hold an expression, preventing it from being canonicalized or evaluated until ReleaseHold is applied to it
Hold(1 + 2)
// ➔ Hold(1 + 2)
HoldValues
(any, any?) -> expression
HoldValues(body): evaluate body with its assigned free symbols shielded — each such symbol becomes a pure symbol (its declared type and in-scope assumptions apply, its assigned value does NOT) for the duration. The value-blind counterpart of evaluating body directly; analogous to Mathematica's Block[{x}, …].
HoldValues(body, [x, y]): shield only the listed symbols (a List, Set, Tuple, or a single symbol); every other symbol resolves normally.
Constants (pi, exponentialE, …) are never shielded, assumptions survive the shield, and the global values are intact afterwards.
let x = 5
let y = 2
(x + y, HoldValues(x + y), HoldValues(x + y, [y]))
HoldValues(body) evaluates body with its assigned free symbols shielded:
during the evaluation, each of them is a symbol with no value, but its type
and the assumptions about it still apply. With a second argument, a list or
a single symbol, only those symbols are shielded. Built-in constants are
never shielded, and the values are intact afterwards. This is Mathematica's
Block[{x}, …].
let x = 5
let a = 3
[together(1/x + a/x^2), HoldValues(together(1/x + a/x^2))]
// ➔ [8/25,(a + x) / x^2]
let x = 5
let a = 3
HoldValues(x^2 + a, [a])
// ➔ a + 25
simplify evaluates its argument first, so HoldValues is how an assigned
symbol stays symbolic through it:
let w = 5
[simplify(abs(w)), HoldValues(simplify(abs(w)), w)]
// ➔ [5,abs(w)]
MathJSON: HoldValues
["HoldValues", body], ["HoldValues", body, symbols], where symbols is a
List, Set, Tuple or a symbol.
HorizontalSpacing
(number) -> nothing
Horizontal spacing annotation.
identity
MathJSON Identity · (T) -> T where T
- argument 1 — The value to return. Sample:
x + 1.
Return the argument unchanged
identity(x + 1)
// ➔ x + 1
IndexedSequence
(any, symbol, any, any?) -> expression
Indexed sequence \{a_n\}_{n=1}^{\infty} — inert head IndexedSequence(term, index, lower, upper?); not evaluated.
IndexedSequence(1/n, n, 1, oo)
// ➔ {1 / n : n = 1..+oo}
The indexed family whose term is term, with the index ranging from lower,
up to upper when it is given. It is inert: evaluate and simplify
leave it unchanged, and it has no collection operations yet.
IndexedSequence(1/n, n, 0)
// ➔ {1 / n : n = 0..}
simplify(IndexedSequence(1/n, n, 1, oo))
// ➔ {1 / n : n = 1..+oo}
MathJSON: IndexedSequence
["IndexedSequence", term, index, lower],
["IndexedSequence", term, index, lower, upper].
The LaTeX sequence-braces notation \{a_n\}_{n=1}^{\infty} parses to
["IndexedSequence", ["a_", "n"], "n", 1, "PositiveInfinity"]. The term is in
the operator-call form ["a_", "n"], so that the binding of the index is
kept. A set-membership subscript gives the least element of the set as the
lower bound: \{a_n\}_{n\in\mathbb{N}} is
["IndexedSequence", ["a_", "n"], "n", 0]. The bare braces \{a_n\} are
still a Set, and the parenthesized form (a_n)_{n\in\mathbb{N}} is not an
IndexedSequence. The expression round-trips through LaTeX.
input
MathJSON Input · (prompt: string?) console -> nothing | string
prompt— The text displayed before the line is read. Sample:"Your name? ".
Read one line of text from the host: the terminal in a command-line host, the prompt() dialog in a browser. The optional operand is a prompt string, displayed before reading. Evaluates to the line read, without the trailing newline; to nothing at end-of-input (or a canceled dialog). On a host with no interactive input, stays unevaluated. When the host denies console access, evaluates to a capability-denied error.
input("Your name? ")
integerString
(n: broadcastable<integer>, base: broadcastable<integer>?, length: broadcastable<integer>?) -> string
n— The integer; a negative one keeps its sign. Sample:255.base— The base, from 2 to 36, 10 by default. Sample:16.length— The number of digits: fewer digits are padded on the left with zeros, more are cut to the last ones. Sample:8.
integerString(n, base=10, length) return a string representation of the integer n in base base. With length, the digits of |n| are padded on the left with zeros, or cut to the last length digits.
integerString(255, 16)
// ➔ "ff"
integerString(10, 2)
// ➔ "1010"
integerString(5, 2, 8)
// ➔ "00000101"
The base is from 2 to 36, 10 by default. The sign is kept, and an integer
greater than 2^{53} stays exact. A base outside 2 to 36 is an
out-of-range error. A symbol with no value, as the integer or as the base,
leaves the call unevaluated.
integerString(-42)
// ➔ "-42"
integerString(30!)
// ➔ "265252859812191058636308480000000"
integerString(5, 37)
// ➔ error: Runtime error: out of range: 2, 36, 37 at `37`
[integerString(x), integerString(5, b)]
// ➔ [IntegerString(x),IntegerString(5, b)]
With a length, the digits of the absolute value are padded with zeros on the left, or cut to their last digits, and the sign is dropped. The length is at most 1,000,000; a greater length leaves the call unevaluated.
[integerString(-5, 2, 8), integerString(1234, 10, 2)]
// ➔ ["00000101","34"]
integerString broadcasts: applied to a list of integers, it returns a list
of strings.
integerString([1, 2, 10], 2)
// ➔ ["1","10","1010"]
See also digitsFrom and baseForm.
MathJSON: IntegerString
["IntegerString", n], ["IntegerString", n, base],
["IntegerString", n, base, length].
["IntegerString", 255, 16]
// ➔ "ff"
["IntegerString", 5, 2, 8]
// ➔ "00000101"
InvisibleOperator
function
Implicit operator used for juxtapositions such as function application or multiplication.
InvisibleOperator(2, x)
// ➔ 2x
isError
(any) -> boolean
- argument 1 — The expression to test; it is held, so an error in it is inspected, not propagated. Sample:
ln("a").
True if the expression is an error value, or a frozen expression embedding one ("a" + 1). False otherwise. Total.
isError(ln("a"))
// ➔ true
isError(1 + 1)
// ➔ false
isError holds its argument, so the error is not propagated before it is
checked, and it always answers. An expression that embeds an error is
True too, but an error inside a collection is not reported: a collection
that holds an error is still a collection. NaN is not an error.
[isError(1 + 1), isError(x), isError([1, ln("a")]), isError(NaN)]
// ➔ [false,false,false,false]
To read an error rather than detect it, use type, which gives error, or
an Error(…) case of a match.
MathJSON: IsError
["IsError", expr].
["IsError", ["Ln", "'a'"]]
// ➔ "True"
isMissing
MathJSON IsMissing · (any) -> boolean
- argument 1 — The value to test. Sample:
NaN.
True for missing, NaN, or a point whose coordinates are all NaN, regardless of provenance. nothing is not an absent datum.
[isMissing(missing), isMissing(NaN), isMissing(0)]
// ➔ [true,true,false]
Latex
(any+) -> string
Serialize an expression to LaTeX
Latex(sqrt(x) / 2)
// ➔ "\frac{\sqrt{x}}{2}"
Latex(pi / 2)
// ➔ "\frac{\pi}{2}"
MathJSON: Latex
["Latex", expr] is a LatexString.
LatexString
(string) -> string
Value preserving type conversion/tag indicating the string is a LaTeX string
parse(LatexString(#"\frac{1}{2}"#))
MatchesType
(subject: any, type: string | type) -> boolean
True iff the first operand, EVALUATED, is a value of the given type — the engine form of the Epsil x is T test and of match type patterns, which both lower here. The subject is never unwrapped: a type VALUE is a value like any other, so MatchesType(TypeFrom("integer"), "number") is False while MatchesType(TypeFrom("integer"), "type") is True; the type-to-type question is Subtype. A settled subject is decided both ways; a valueless or unresolved subject answers from its static type when that decides it, and stays symbolic otherwise.
MatchesType([1, 2], "list<integer>")
// ➔ true
missing
MathJSON Missing · variable missing
A value that is absent but whose position is preserved (Julia missing, R NA); the sole member of the missing type.
missing + 1
// ➔ missing
Module
(symbol) -> unknown
The definition of a name in the standard library, also where a local definition shadows the name
Module(Pi)
// ➔ pi
apply(Module(Floor), 2.5)
// ➔ 2
std::name is the definition of name in the standard library, also where
a local definition shadows it. A call std::floor(2.5) follows the rules of
the library function. A name that the library does not define is an error.
Module itself cannot be declared or assigned. See
Naming.
let pi = 3
std::pi + pi
// ➔ 3 + pi
Module(Floo)
// ➔ error: not a library name: Floo
MathJSON: Module
["Module", name]. A call of a library function is written with Apply:
["Apply", ["Module", "Floor"], 2.5], whose canonical form is the plain call
bound to the library function. Its arguments read the definitions of the
scope. In a scope that shadows a library name, .json and toMathJson()
write the library definition as ["Module", "Pi"], so that the MathJSON has
the same value when it is read again in that scope. A second operand is
reserved, and is an error. LaTeX has no spelling: ["Module", "Pi"] is
written \pi.
["Module", "Floo"]
// ➔ ["Error", "'not-a-library-name'", "Floo"]
N
(any, (integer | list<number>)?) -> unknown
N(expr): numerically evaluate an expression.
N(expr, precision): evaluate to precision significant digits.
N(expr, [precision, accuracy]): evaluate with a precision goal and an accuracy goal.
N(pi)
// ➔ 3.14159265358979323846
N(1/3, 4)
// ➔ 0.3333
N(exp(100), [positiveInfinity, 20])
// ➔ 2.688117141816135448412625551580013587361111877374192241519160862e+43
The value is computed with the requested digits plus a few guard digits, then rounded, and it keeps these digits. The working precision of the engine does not change, and a later operation on the result uses the working precision.
[N(pi, 20), N(1/3, 4), N(2) / 3]
// ➔ [3.1415926535897932385,0.3333,0.666666666666666666667]
With a list [p, a], N aims at a precision goal p (correct significant
digits) or an accuracy goal a (an absolute error below 10^-a), whichever
is met first; either can be oo. The engine doubles its precision until two
values agree within the goal. A goal that needs more than 1,000 digits, or
cannot be checked, leaves the expression unevaluated.
N(1000pi, [10, 3])
// ➔ 3141.593
MathJSON: N
["N", expr], ["N", expr, precision], ["N", expr, ["List", p, a]]. The
result of N with a precision is a float, also when its value is an integer:
["N", 2, 10] is 2.0. The elements of a list result are rounded floats,
and the constants of a symbolic result stay exact. The value of an exact
rational is a float, so ["N", ["Rational", 1, 3]] has the type
real<0.33..0.34>; an integer stays an integer.
["N", ["Multiply", ["Power", 10, 10],
["Subtract", ["Exp", 100], ["Exp", ["Divide", 999999999999, ["Power", 10, 10]]]]],
["List", "PositiveInfinity", 20]]
// ➔ 2.688117141681729591326298974395630530648558808379370953675983977e+43
nSolve
MathJSON NSolve · (any, any*) -> list
- argument 1 — The equation, an expression read as
= 0, or a list of equations. Sample:x^2 == 2. - arguments 2, … — An unknown, a list of unknowns, or a domain spec as for
Solve; by default, the free variable of the equation. Sample:x.
NSolve(equation, unknown): the solutions of an equation as floats.
It is Mathematica nSolve: it takes the same operands as solve, including domain specs and systems of equations, and gives the N of each solution of solve, so nSolve(x^2 == 2, x) → [1.414…, -1.414…]. When solve finds no solution set, nSolve stays unevaluated: for a polynomial solve already gives numeric roots when there is no closed form, and findRoot gives one local root from a start value.
nSolve(x^2 == 2, x)
// ➔ [1.4142135623730950488,-1.4142135623730950488]
NamedArgument
(string, any) -> nothing
NamedArgument(name, value): one named argument of a call (Epsil surface syntax: f(rate: 0.05)).
A parse-level carrier, like Spread, but one that never survives: the enclosing call consumes it at canonicalization, permuting the written arguments into the order its callee declares.
Reaching this definition therefore means the carrier was NOT consumed — the callee supplied no parameter names to match — which is the argument-names-unavailable error.
((x, y) => x - y)(y: 2, x: 10)
// ➔ 8
nothing
variable nothing
The value of an empty block or of a statement with no value; the sole member of the unit type. A list keeps it as an element.
[1, nothing, 2]
// ➔ [1,nothing,2]
nothing is kept where it is written, and an operation that needs a value
gives an incompatible-type error for it:
[2, nothing, 3]
// ➔ [2,nothing,3]
1 + nothing
// ➔ error: Type error: expected `number`, got `nothing` at `nothing` in `1 + nothing`
MathJSON: Nothing
"Nothing". An empty slot in LaTeX, such as \lbrack 2, ,3 \rbrack, is a
parse error: the slot holds ["Error", "'missing'"]. A trailing comma,
\lbrack 1, 2, \rbrack, is dropped. The symbols All and None are inert
tags of the MathJSON format, with no value other than themselves.
numberFrom
(s: character | string, base: (character | integer | string)?) -> number
s— The numeral; text that is not a numeral is an error value. Sample:"3.25".base— The base, from 2 to 36; with a base, only an integer numeral is accepted. Sample:16.
NumberFrom(s): the number the string s denotes — optional surrounding whitespace, an optional sign, then ASCII digits with an optional "." fraction and an optional e/E exponent, or one of "oo", "+oo", "-oo", "NaN", "Indeterminate". The integer part may be omitted before a fraction (".5" is 0.5); a trailing "." with no fraction digits ("5.") is not accepted. Any other text, including "", is an error value (never NaN).
NumberFrom(s, base): the integer s denotes in base (2 to 36); only integer numerals are accepted.
numberFrom("3.25")
// ➔ 3.25
numberFrom("ff", 16)
// ➔ 255
Unlike digitsFrom, which reads integers only, numberFrom
reads fractions, exponents and the spellings of the infinities and NaN.
The grammar is fixed, so that hosts cannot differ: any amount of Unicode
White_Space before and after, an optional + or - sign, then either a
decimal numeral (ASCII digits, an optional . and fraction, an optional e
or E exponent) or one of the spellings oo, +oo, -oo, NaN,
Indeterminate.
| Input | Result | Why |
|---|---|---|
"42", "-42", "+7", " 42 " | 42, -42, 7, 42 | An integer numeral, with a sign and whitespace around it |
"3.14", "1e-3", "1.5e3" | 3.14, 0.001, 1500 | A fraction and an exponent |
".5" | 0.5 | A leading . needs no integer part |
"oo", "+oo", "-oo", "NaN", "Indeterminate" | +oo, +oo, -oo, NaN, NaN | The spellings of Epsil for the infinities and NaN |
"5." | invalid-number error | A . with no fraction digits after it is not a numeral |
"" | invalid-number error | The empty string is not a number |
"abc", "12abc" | invalid-number error | The whole string must be a numeral, not only its start |
"1/3" | invalid-number error | Not a numeral: make the fraction with arithmetic |
"0x1f", "1_000", "Infinity", "nan" | invalid-number error | Not in the grammar: the spellings are exact, and case-sensitive |
"٣" (Arabic-Indic three) | invalid-number error | ASCII digits only, so that digits that look alike cannot pass |
[numberFrom(" +7 "), numberFrom("1e-3"), numberFrom(".5")]
// ➔ [7,0.001,0.5]
[numberFrom("oo"), numberFrom("-oo"), numberFrom("NaN")]
// ➔ [+oo,-oo,NaN]
numberFrom("5.")
// ➔ error: Runtime error: invalid number: 5. at `"5."`
numberFrom("٣")
// ➔ error: Runtime error: invalid number: ٣ at `"٣"`
A failure is always an error value, never NaN: NaN is the result of
reading "NaN", so it cannot also mean that the reading failed.
isError(numberFrom("12abc"))
// ➔ true
A numeral with no fraction and no exponent gives an exact integer. A numeral
with a fraction or an exponent gives an exact decimal, which N
approximates.
With a base (2 to 36), as for digitsFrom, only integer numerals are read:
numberFrom("1010", 2)
// ➔ 10
numberFrom("1.5", 16)
// ➔ error: Runtime error: invalid number: 1.5 at `"1.5"`
numberFrom("11", 37)
// ➔ error: Runtime error: unexpected base: 37 at `37`
See also digitsFrom, integerString and
String.
MathJSON: NumberFrom
["NumberFrom", s], ["NumberFrom", s, base].
["NumberFrom", {str: "-1.5e2"}]
// ➔ -150
["NumberFrom", {str: "ff"}, 16]
// ➔ 255
numericApproximation
MathJSON NumericApproximation · (any) -> unknown
- argument 1 — The expression to approximate. Sample:
sqrt(2).
Numerically evaluate an expression, as the .N() method does (engine-internal).
numericApproximation(sqrt(2))
// ➔ 1.4142135623730950488
Object
(any, string?) -> unknown
Provenance head for the snapshot of a mutable object: ["Object", <record>, "'TypeName'"]. The record holds the object's stored fields at the moment it was serialized; the second operand names the nominal type the object had. Not a constructor and not an ascription — it wraps data, it does not make an object.
Optional
(any, any) -> nothing
Optional(param, default): a parameter of a function literal with a default value (Epsil surface syntax: (x, k = 2) => x * k).
A call that leaves out the argument of the parameter receives the default. param is a symbol or Typed(symbol, type); default is a number, a string, True, False, a symbol, [] or {}.
A parse-level carrier, like Spread: only the parameter list of a Function literal reads it. Anywhere else it is the unexpected-argument error.
((x, k = 2) => x * k)(3)
// ➔ 6
OverParen
(any+) -> expression
Over-paren accent (\overparen{BC}) — opaque typed head; not evaluated.
OverParen(B, C)
// ➔ OverParen(B, C)
MathJSON: OverParen • LaTeX: \overparen
padEnd
MathJSON PadEnd · (s: character | string, n: integer, pad: (character | string)?) -> string
s— The text to pad. Sample:"abc".n— The length of the result, in characters, a non-negative integer; a shortersis padded, a longer one returned unchanged. Sample:6.pad— The padding, repeated and cut to fit, a space by default; it must not be empty. Sample:".".
PadEnd(s, n, pad=" "): s padded at the END to n characters by repeating pad (its final copy truncated on a character boundary). Returned unchanged when s already has n or more characters. n must be a non-negative integer; an empty pad is an error; a non-string pad leaves the expression unevaluated.
padEnd("abc", 6, ".")
// ➔ "abc..."
padStart
(s: character | string, n: integer, pad: (character | string)?) -> string
s— The text to pad. Sample:"42".n— The length of the result, in characters, a non-negative integer; a shortersis padded, a longer one returned unchanged. Sample:5.pad— The padding, repeated and cut to fit, a space by default; it must not be empty. Sample:"0".
PadStart(s, n, pad=" "): s padded at the START to n characters by repeating pad (its final copy truncated on a character boundary). Returned unchanged when s already has n or more characters. n must be a non-negative integer; an empty pad is an error; a non-string pad leaves the expression unevaluated.
padStart("42", 5, "0")
// ➔ "00042"
padStart adds copies of the padding before the string and padEnd after
it, until the string has the given number of characters. A string that
already has that many characters or more is returned unchanged.
[padStart("7", 3, "0"), padEnd("7", 3, "0"), padStart("abc", 2, "0")]
// ➔ ["007","700","abc"]
The padding is a space by default. A padding of several characters is repeated, and its last copy is cut at a character boundary to fit exactly.
padStart("ab", 3)
// ➔ " ab"
padEnd("ab", 7, "123")
// ➔ "ab12312"
padStart("ab", 4, "👨👩👧x")
// ➔ "👨👩👧xab"
The length must be a non-negative integer. An empty padding is an error: it cannot reach the length, and returning the string unchanged would hide the mistake.
padStart("ab", 4, "")
// ➔ error: Runtime error: unexpected argument
Padding counts characters, not display columns: it does not align text in a terminal or in a proportional font.
MathJSON: PadStart
["PadStart", s, n], ["PadStart", s, n, pad], and likewise PadEnd.
["PadStart", {str: "7"}, 3, {str: "0"}]
// ➔ "007"
["PadEnd", {str: "ab"}, 7, {str: "123"}]
// ➔ "ab12312"
parallel
(any, any) -> expression
- argument 1 — A line or a segment. Sample:
l. - argument 2 — The other line or segment. Sample:
m.
Parallelism relation (AB \parallel CD) — opaque typed head; not evaluated.
parallel(l, m)
// ➔ Parallel(l, m)
MathJSON: Parallel • LaTeX: \parallel
parse
(string) any -> any
- argument 1 — The LaTeX source; an empty string gives
Nothing. Sample:"x^2 + 1".
Parse a LaTeX string and evaluate to a corresponding expression
parse(#"\frac{\pi}{2}"#)
parse evaluates the expression that it reads, so parse("x + x") with
x = 3 is 6. An operator that holds its argument, such as solve, D,
integrate, limit and expand, reads the parsed expression without
evaluating it.
parse("\\frac{\\pi}{2}")
// ➔ 1/2 * pi
D(parse("y^2"), y)
// ➔ 2y
MathJSON: Parse
["Parse", ["LatexString", "'\\frac{\\pi}{2}'"]].
perpendicular
(any, any) -> expression
- argument 1 — A line or a segment. Sample:
l. - argument 2 — The other line or segment. Sample:
m.
Perpendicularity relation (AB \perp CD) — opaque typed head; not evaluated.
perpendicular(l, m)
// ➔ Perpendicular(l, m)
MathJSON: Perpendicular • LaTeX: \perp
Pipe
(value, function) -> unknown
Apply a function to a value: Pipe(x, f) evaluates to f(x).
Pipe([3, 1, 2], sort)
// ➔ [1,2,3]
16 |> sqrt
// ➔ 4
The pipeline |> is described in Pipe and
Pipelines. The right-hand side must be a
function: a number, a string or a boolean is an incompatible-type error.
A name with no definition is not an error: the pipe gives a call, which
evaluates once the name has a definition. This differs from apply, which
reads a value that is not a function as a constant function.
5 |> 3
// ➔ error: Type error: expected `function`, got `3` at `3` in `5 |> 3`
x |> f
// ➔ f(x)
A function whose variable can be inferred, such as solve, D, series
and the polynomial functions, can be a stage without the variable:
x^2 == 4 |> solve
// ➔ [2,-2]
MathJSON: Pipe • LaTeX: \rhd
["Pipe", value, function] evaluates to [function, value]. A call stage
missing required arguments receives the value as its first argument, and a
unary function literal maps over a list:
["Pipe", ["Range", 1, 10], ["Take", 3]]
// ➔ ["Take", ["Range", 1, 10], 3]
["Pipe", ["List", 1, 2, 3], ["Function", ["Power", "x", 2], "x"]]
// ➔ ["List", 1, 4, 9]
In LaTeX, the pipe is \rhd, \triangleright, \vartriangleright, ⊳
or |>. A \square in the right-hand side is the position of the piped
value (_ in Epsil): x^2 = 4 \rhd \operatorname{Solve}(\square, x) is
["Solve", ["Equal", ["Power", "x", 2], 4], "x"]. A function command with
no argument, such as \ln, \lb or \sqrt, is a function value:
12 \rhd \ln is \ln(12). The prefix form, \rhd f with no left-hand
side, is the function of one argument that applies f to it.
prime
(T, integer?) -> T where T
- argument 1 — The primed expression, often a function. Sample:
f. - argument 2 — The order of the derivative; by default, 1. Sample:
2.
Derivative or prime notation (f', f^{(n)}) — opaque typed head until a derivative library handler runs.
prime(f)
// ➔ Prime(f)
MathJSON: Prime • LaTeX: ^\prime
print
MathJSON Print · (any*) console -> nothing
- arguments 1, … — A value to print; a string prints its content, without the quotes. Sample:
"Hello".
Print the operands to the host console, separated by spaces and followed by a newline. String operands print their content (without quotes); other expressions print their text form. Evaluates to nothing. On a host without a console, prints nothing. When the host denies console access, evaluates to a capability-denied error.
print("Hello", 42)
program
(unknown*) -> unknown
- arguments 1, … — A statement; a statement that gives an error does not stop the program. Sample:
x + 1.
Evaluate a program in the caller scope, continuing after statement errors, and return the value of its last statement.
program(error("boom"), 2 + 3)
// ➔ 5
The source of an Epsil program, a file or the text of epsil -e, is a
Program. It evaluates its statements in the caller's scope, so its
declarations stay available after it: each entry of the REPL is a program,
and the next entry sees its declarations. A braced sequence inside a
program is a Block, whose declarations are
local.
Type and protocol declarations are prepared first, then the function
statements and the signatures that go with them, then the other statements
in source order. So a function statement can be called before it is
written, and its clauses can be spread over the program. A variable whose
value is a function follows the order of the statements instead.
g(2)
function g(x) { x + 1 }
// ➔ 3
h(2)
let h = x => x + 1
// ➔ error: Static error: `h` is used before the statement that declares it in this block in `h(2)`
A declaration sets the contract of its variable. Without an annotation, a
variable whose value is a number has the type number, and one whose
value is a function has the type function. A function stored in a
variable keeps its own argument checks, defaults and closure, and a new
function assigned to the variable does not make a new contract. An
annotation is a contract too, and a const rejects every assignment.
let x = 1
x = 2.5
x
// ➔ 2.5
let f = x => x + 1
f = x => x * 2
f(3)
// ➔ 6
let f = x => x + 1
f = 3
// ➔ error: Static error: `f` has the type `function`, and the value has the type `3` in `f := 3`
const c = 1
c = 2
// ➔ error: Static error: cannot assign a value to the constant `c` in `c := 2`
Two declarations of one name in one program are an error. A declaration in a later program, such as the next entry of the REPL, can replace an earlier declaration and give the name a new type.
let a = 1
let a = 2
// ➔ error: Static error: variable redeclaration: a in `let a = 2`
The value of a program is the value of its last statement, or nothing
for an empty program and for one that ends with a declaration or an
assignment. An ordinary error in a statement is reported, and the next
statement is evaluated: the CLI then prints the error and exits with
status 1. A cancellation, such as the time limit, stops the program.
An assignment to a name that the program does not declare is an error:
c = 5
c
// ➔ error: Static error: `c` is not declared: write `let c = …` in `c := 5`
MathJSON: Program
["Program", statement-1, …, statement-n]. The Epsil parser always returns
a Program, also for an empty source and for a single expression.
["Program", ["Declare", "b", "'unknown'", 2], "b"]
// ➔ 2, and b remains declared in the caller's scope
ProtocolDefault
constant unknown
Stands for the default value of a parameter in a call of a protocol member: the call receives the default that the selected requirement declares for that parameter.
protocol Scaled { function scale(self: Self, by: real = 2, shift: real = 0) -> real }
type number is Scaled { function scale(self, by, shift) -> real { self * by + shift } }
scale(5, shift: 1)
ProtocolMember
(protocol: string, member: string, arguments: any*) -> unknown
Invoke a protocol member on a value — the lowering of a QUALIFIED protocol call (Comparable.compare(x, y) in Epsil, whose parse, a MemberCall on the protocol name, canonicalizes to apply(field(Comparable, "compare"), x, y)). The first two operands name the protocol and the member; the rest are the call arguments. Dispatch is dynamic and restricted to the named protocol: the most specific conformance implementation for the runtime type of the first argument is invoked. Several equally specific implementations are protocol-call-ambiguous; none is protocol-implementation-missing; an argument whose type cannot decide the question leaves the call symbolic.
protocol Negatable { function negated(self: Self) -> Self }
type number is Negatable { function negated(self) -> number { -self } }
Negatable.negated(5)
ProtocolProperty
(protocol: string, property: string, receiver: any, value: any?) -> unknown
Read (or write) a protocol PROPERTY through a NAMED protocol — the lowering of the qualified field form person.(Nameable.name) (protocols design P6, amending the D16 field grammar). The first two operands name the protocol and the property; the third is the receiver. A fourth operand makes it a property STORE — the qualified write person.(Nameable.name) = v — which invokes the set accessor against the receiver, discards what it returns, and evaluates to the value assigned; a receiver that is not an object is immutable-value-assignment. Dispatch is dynamic and restricted to the named protocol: the most specific conformance implementation for the runtime type of the receiver is invoked.
protocol Signed { readonly sign: string }
type number is Signed {
get sign(self) -> string { if (self < 0) { "-" } else { "+" } }
}
let x = -12
x.(Signed.sign)
quadrilateral
(any+) -> expression
- arguments 1, … — A vertex of the quadrilateral. Sample:
A.
Quadrilateral mark (\square ABCD) — opaque typed head; not evaluated.
quadrilateral(A, B, C, D)
// ➔ Quadrilateral(A, B, C, D)
MathJSON: Quadrilateral • LaTeX: \square
random
((collection<any> | set<real>)?) random -> any
- argument 1 — The domain: a real is drawn from an interval, an element from a range or a finite non-empty collection; by default, a real in [0, 1). Sample:
1..6.
Random(): non-deterministic real in [0, 1)
Random(Interval(a, b)): a real in [a, b) (endpoint markers ignored)
Random(Range(...)): an element of the range.
Random(xs): an element of the finite collection xs.
random()
random(1..6)
random is not a pure function: it has the random effect, and it gives a
different value each time it is evaluated. Inside withRandomSeed, the block
as a whole is pure and replays.
random()is a real number in[0, 1).random(interval(a, b))is a real number in[a, b). Open and closed ends are ignored: a floating-point draw cannot respect an open end.random(m..n)is an element of the range, which includes both ends. A range with reversed bounds descends.random(xs)is an element of the finite collectionxs. The domain is not built:random(1..1000000)picks an index of the range.
random draws along the first axis of a nested collection, so
random([[1, 2], [3, 4]]) is a row. A tuple is a finite indexed collection,
and random gives one of its elements. An unbounded or empty interval, an
infinite range or collection, and an empty collection are errors.
random([])
// ➔ error: Runtime error: out of range: a non-empty collection, []
random([[1, 2], [3, 4]])
random(interval(-1, 1))
random([5, 2, 10, 18])
MathJSON: Random
["Random"], ["Random", domain].
["Random", ["Range", 1, 6]]
// ➔ 4 (for example), a die roll
["Random", ["Interval", -1, 1]]
// ➔ -0.318… (for example)
randomChoice
((T, k: number) random -> T where T: string) & ((collection<any> | set<real>, k: number) random -> list<any>)
- argument 1 — The domain to draw from, as for
Random; a string gives a string of its characters. Sample:["a", "b", "c"]. k— The number of draws, from 0 to 1,000,000; it may exceed the size of the domain. Sample:5.
RandomChoice(domain, k): a list of k independent draws from domain, with replacement. k may exceed the size of the domain — that is what replacement means. Choosing from a string yields a string.
randomChoice(["a", "b", "c"], 5)
The count k is a number, not an integer, so a computed count need not
be rounded first: it is rounded half toward +oo (2.5 gives 3, -2.5
gives -2). A negative or out-of-range count is an error, and 0 gives the
empty list. Only the k drawn elements are built, not the domain, so
randomChoice(1..1000000000, 5) is cheap.
[randomChoice(1..6, 0), length(randomChoice(1..6, 2.5))]
// ➔ [[],3]
withRandomSeed(7, randomChoice(interval(0, 1), 4))
// ➔ [0.08483070468009213,0.19562714896013578,0.24148300073452322,0.750274109006007]
randomChoice(1..6, -1)
// ➔ error: Runtime error: out of range: a count in 0..1000000, -1
MathJSON: RandomChoice
["RandomChoice", domain, k].
["RandomChoice", ["Range", 1, 6], 3]
// ➔ [4, 1, 4] (for example): repeats are expected
randomExpression
MathJSON RandomExpression · () entropy -> expression
Generate a random expression.
randomExpression()
ReleaseHold
(any) -> unknown
Release an expression held by Hold
ReleaseHold(Hold(1 + 2))
// ➔ 3
replaceAll
MathJSON ReplaceAll · (any, any+) -> any
- argument 1 — The expression in which to replace; it is evaluated after the replacement. Sample:
x^2 + x. - arguments 2, … — A rule, or a list of rules; all the rules are applied at once, in a single pass. Sample:
Rule(x, 3).
ReplaceAll(expr, rules): apply one or more replacement rules to expr, then evaluate the result (Mathematica expr /. rules).
A rule is Rule(lhs, rhs), or lhs -> rhs in LaTeX (parsed as to; in Epsil -> builds a dictionary entry, which is not a rule). Several rules may be given as extra arguments or as a List/set of rules; they are applied simultaneously in a single pass.
replaceAll(x^2 + x, Rule(x, 3))
// ➔ 12
Rule
(match: expression, replace: expression, predicate: function?) -> expression
Pattern replacement rule.
replaceAll(x + y, Rule(x, 2))
// ➔ y + 2
RuntimeError
(expression<ErrorCode> | string) -> never
Construct an error value when evaluated: the runtime counterpart of a written Error(…), which is a static diagnostic node. Evaluates to error(code).
isError(RuntimeError("oops"))
// ➔ true
Sequence
function
Ordered sequence of expressions.
[0, Sequence(1, 2), 3]
// ➔ [0,1,2,3]
When a sequence is used where an element is expected, its elements are spliced into the enclosing expression. The empty sequence splices to no element.
let s = Sequence(2, 3); [1, s, 4]
// ➔ [1,2,3,4]
[1, Sequence(), 2]
// ➔ [1,2]
Nothing is not an empty sequence. It is the value of an empty block or of a
statement with no value, and a collection keeps it as an element:
[1, Nothing, 2]
// ➔ [1,nothing,2]
length([1, Nothing, 2])
// ➔ 3
MathJSON: Sequence
["Sequence", ...elements].
["List", 1, ["Sequence", 2, 3], 4]
// ➔ ["List", 1, 2, 3, 4]
["List", 1, ["Sequence"], 2]
// ➔ ["List", 1, 2]
["List", 1, "Nothing", 2]
// ➔ ["List", 1, "Nothing", 2]
Signature
(symbol) -> nothing | string
Return the signature string of an operator.
Signature(stringRepeat)
// ➔ "(character | string, n: integer) -> string"
simplify
MathJSON Simplify · (any, assumptions: any?) -> expression
- argument 1 — The expression to simplify. Sample:
sin(x)^2 + cos(x)^2. assumptions— A boolean assumption, or a list of them, that holds during the simplification only. Sample:x > 0.
Simplify(expr): simplify an expression.
Simplify(expr, assumptions): simplify under one or more boolean assumptions (e.g. x > 0), or a List/And of them. The assumptions hold only for the duration of the simplification.
simplify(sin(x)^2 + cos(x)^2)
// ➔ 1
simplify(sqrt(x^2), x > 0)
// ➔ x
solve
(any, any*) -> list
- argument 1 — An equation, a bare expression read as
= 0, or a list of equations. Sample:x^2 - 1 == 0. - arguments 2, … — The unknown, or a list of unknowns for a system; by default, the equation's single free variable. Sample:
x.
Solve(equation, unknown): the list of solutions of an equation for the unknown. The equation may be an Equal expression or a bare expression (read as = 0), e.g. solve(x^2 - 1 == 0, x) or solve(x^2 - 1, x).
The unknown may be omitted: it defaults to the equation's single free variable, or to x when there are several and one of them is x.
Solve([eq1, eq2, …], [x, y, …]): solve a system of equations; each solution is a tuple of values in the order of the variable list, e.g. Solve([x + y == 3, x - y == 1], [x, y]) → [(2, 1)].
solve(x^2 - 1 == 0, x)
// ➔ [1,-1]
solve([x + y == 3, x - y == 1], [x, y])
// ➔ [(2, 1)]
solve(equation, unknown) is the list of the solutions. The equation is an
== equation, or an expression solved as equal to zero. With no unknown, it
is the single free variable of the equation, or x when there are several
and one of them is x, so a pipeline works without naming it. For a system,
give a list of equations and a list of unknowns: each solution is a tuple, in
the order of the unknowns. Linear systems are solved exactly.
[solve([x + y == 3, x - y == 1], [x, y]), x^2 == 4 |> solve]
// ➔ [[(2, 1)],[2,-2]]
A domain. An unknown can be restricted to a domain, x in 1..1000 or
x in interval(a, b). The equation is solved symbolically, and its solutions
are filtered to the domain. A periodic family gives every member in the
domain. When no symbolic solution is found and the domain is finite and not
too large, solve checks each element exactly. With a condition, any
boolean expression is accepted. With several unknowns, each with a domain,
each solution is a tuple:
solve(x^2 - 5x == -6, x in 1..1000)
// ➔ [3,2]
solve(x^3 + y^3 == 1729, x in 1..12, y in 1..12)
// ➔ [(1, 12),(9, 10),(10, 9),(12, 1)]
Integer equations are solved symbolically when every unknown ranges over
integers: linear equations in any number of unknowns, Pell equations
x^2 - D y^2 = N, and the Pythagorean equation x^2 + y^2 = z^2. This
reaches answers that checking each element cannot: the domain below has
10^10 pairs. Over all integers, the result is a family with integer
parameters, ArbitraryInteger(1), ArbitraryInteger(2), … For the
Pythagorean equation, it is the two classical families, which hold every
integer solution.
solve(x^2 - 29y^2 == 1, x in 1..100000, y in 1..100000)
// ➔ [(9801, 1820)]
solve(6x + 9y == 4, x in 1..100, y in 1..100)
// ➔ []
solve(3n + 4m == 7, n in Integers, m in Integers)
// ➔ [(-7 + 4ArbitraryInteger(1), 7 - 3ArbitraryInteger(1))]
The assumptions about an unknown, such as assume(n > 0), filter the
solutions too.
The result is complete or absent. The list holds every solution in the
domain, and an empty list means that there is none. When the engine cannot
show that its list is complete, solve stays unevaluated: it never returns a
part of the solutions. An equation that holds for every value gives
[ArbitraryConstant(1)], and an equation whose answer depends on another
unknown stays unevaluated.
[solve(e^x == x + 2, x), solve(x == x, x), solve(a == 0, x)]
// ➔ [Solve(e^x == x + 2, x),[ArbitraryConstant(1)],Solve(a == 0, x)]
Real or complex solutions. With no declared type and no domain, a
polynomial equation gives all its roots, the complex ones too. A root is
exact when the polynomial has a closed form that the engine knows: a rational
root, a quadratic factor with rational coefficients, a pure power x^n = c,
or a polynomial in x^g; the other roots are floats. An exponential
equation with an exponent linear in the unknown gives its complex roots, a
family with the period 2πi and an integer parameter,
ArbitraryInteger(1); over the real numbers it gives the real roots only.
Any other equation gives its real solutions only. A symbol other than the
unknown, with no value and no type, counts as real.
[solve(x^2 + 1 == 0, x), solve(x^3 == 8, x)]
// ➔ [[i,-i],[2,-1 + sqrt(3) * i,-1 - sqrt(3) * i]]
[solve(e^x == -1, x), solve(e^x == -1, x in RealNumbers)]
// ➔ [[2i * pi * ArbitraryInteger(1) + i * pi],[]]
[solve(abs(x - 1) == 3, x), solve(abs(x - a) == 2, x)]
// ➔ [[-2,4],[a - 2,a + 2]]
Trigonometric equations have infinitely many solutions. With no domain,
or over the real or complex numbers, the result is a list of families with an
integer parameter, ArbitraryInteger(1). Families with the same solutions
become one family, and each factor of a product gives its families with its
own period. A condition on the unknown cannot remove members of a family, and
then solve stays unevaluated. Over a bounded domain, the result holds every
solution in the domain.
solve(sin(x) == 1/2, x)
// ➔ [2pi * ArbitraryInteger(1) + 1/6 * pi,2pi * ArbitraryInteger(1) + 5/6 * pi]
[solve(sin(x) == 0, x), solve((x - 1) * sin(x) == 0, x)]
// ➔ [[pi * ArbitraryInteger(1)],[1,pi * ArbitraryInteger(1)]]
solve(sin(x) == 0, x in interval(0, 10))
// ➔ [0,pi,2pi,3pi]
A decimal number in the equation. The engine compares two numbers
exactly, with no tolerance, so 10 == 10.0000000000001 is False. The
solutions are the exact roots, with the decimal numbers as they are written,
and over a discrete domain each element is checked exactly.
solve(x == 10.0000000000001, x)
// ➔ [10.0000000000001]
[solve(x == 10.0000000000001, x in -10..10), solve(x == 10, x in -10..10)]
// ➔ [[],[10]]
When solve stays unevaluated, the reason is usually one of these: the
unknown is both inside and outside a function that the solver cannot invert
(e^x = x + 2, cos(x) = x); a special function of the unknown
(besselJ(0, x) = 0); a trigonometric function of an argument that is not
linear in the unknown, with no bounded domain (sin(x^2) = 0); a polynomial
of degree 3 or more with symbolic coefficients; or, over a bounded domain,
too many solutions to list. Then:
- give a bounded domain,
x in interval(a, b): the engine uses interval arithmetic to prove that the domain has no other root; - or use
findRootto find one solution numerically, near a start value.
findRoot(e^x == x + 2, [(x, 1)])["converged"]
// ➔ true
MathJSON: Solve
["Solve", equation], ["Solve", equation, unknown],
["Solve", equation, spec1, spec2, ...], where a spec is a symbol,
["Element", symbol, collection], or ["Element", symbol, collection, condition]
with the indexing-set convention of Sum. In LaTeX, x \in 1..1000 parses
to the Element form: \operatorname{Solve}(x^2=4,\; x \in 1..1000).
["Solve", ["Equal", ["Power", "x", 2], 1], "x"]
// ➔ ["List", 1, -1]
["Solve",
["List", ["Equal", ["Add", "x", "y"], 3], ["Equal", ["Subtract", "x", "y"], 1]],
["List", "x", "y"]]
// ➔ ["List", ["Tuple", 2, 1]]
Solve is the operator form of the expr.solve() method of the JavaScript
API. For a periodic equation, Solve gives the families of solutions, and
expr.solve() the principal solutions. A root template added to
ce.solveRules is taken as a solution as it is.
Spread
(any) -> unknown
Spread(t): splice the elements of the tuple t into the enclosing argument list (Epsil surface syntax: f(...t)).
A literal tuple splices at canonicalization; a symbolic argument is spliced by the enclosing call at evaluation (step 0 of the evaluate path), which re-validates the resulting arity.
max(...(4, 9, 2))
// ➔ 9
String
(any*) -> string
A string created by joining its arguments. The arguments are converted to their default string representation.
String("x", 2)
// ➔ "x2"
String(x, 2)
// ➔ "x2"
String("Hello", ", ", "🌍", "!")
// ➔ "Hello, 🌍!"
String(42, " is the answer")
// ➔ "42 is the answer"
With exactly one argument that is a finite collection, String joins the
elements of the collection instead of broadcasting over them. This is what
makes String(characters(s)) == s hold. With one infinite collection, it
stays unevaluated.
[String(characters("abc")), String([1, 2, 3])]
// ➔ ["abc","123"]
String(characterFrom("x"))
// ➔ "x"
String(1..oo)
// ➔ String(1..oo)
With more than one argument, String broadcasts over a collection argument,
and a string argument stays whole (see
Strings stay whole under broadcast and flattening).
String("x", [1, 2])
// ➔ ["x1","x2"]
String("ab", 1)
// ➔ "ab1"
MathJSON: String • LaTeX: \text
["String", expr1, expr2, ...].
["String", {str: "Hello"}, {str: ", "}, {str: "🌍"}, {str: "!"}]
// ➔ "Hello, 🌍!"
["String", ["Characters", {str: "abc"}]]
// ➔ "abc"
["String", {str: "x"}, ["List", 1, 2]]
// ➔ ["List", "'x1'", "'x2'"]
stringCompare
(character | string, character | string) -> integer
- argument 1 — The first string. Sample:
"apple". - argument 2 — The second string. Sample:
"banana".
StringCompare(a, b): -1 when a sorts before b, 0 when they are equal, 1 when a sorts after b. The order compares Unicode scalar sequences code point by code point (NOT UTF-16 code units, which would sort astral characters below U+E000..U+FFFF).
stringCompare("apple", "banana")
// ➔ -1
The order is the order of the Unicode code points of the NFC forms, compared one position at a time. A string that is a proper prefix of another comes first. The order is not locale-aware, so that the identity of values, keys and match plans is the same on every host. A locale-aware collation would be a new argument, not a change to this order.
stringCompare("ab", "abc")
// ➔ -1
stringCompare("e\u{301}", "é")
// ➔ 0
Where this differs from <
< and the other comparison operators compare two strings by their UTF-16
code units. That puts the characters from U+10000 up, which are encoded with
surrogates from U+D800, before the characters from U+E000 to U+FFFF.
stringCompare puts them after, as their code points do. For all other
text, every character below U+D800 (Latin, Greek, Cyrillic, CJK), the two
orders are the same. Use stringCompare when the order must be that of the
code points.
stringCompare("\u{E000}", "\u{1F600}")
// ➔ -1
"\u{E000}" < "\u{1F600}"
// ➔ false
MathJSON: StringCompare
["StringCompare", a, b].
["StringCompare", {str: "a"}, {str: "b"}]
// ➔ -1
["StringCompare", {str: "ab"}, {str: "abc"}]
// ➔ -1
stringFrom
(any, format: string?) -> string
- argument 1 — The value to convert; with no format, an integer or a list of integers is read as Unicode scalar values. Sample:
65. format— The format:"default","unicode-scalars","utf-8"or"utf-16". Sample:"utf-8".
StringFrom(value, format?): create a string from value. With no format, a number or a list of numbers is read as Unicode scalar values (stringFrom(65) is "A"), and any other value is printed (stringFrom(True) is "True"). The formats are "default" (print the value), "unicode-scalars", "utf-8" and "utf-16".
stringFrom(65)
// ➔ "A"
stringFrom([72, 105])
// ➔ "Hi"
| Format | The argument is |
|---|---|
| (none) | A finite non-negative integer, or a list of them, is read as Unicode scalars. Any other value is printed. |
"default" | Printed, as the default string representation of the value |
"utf-8" | A collection of UTF-8 bytes |
"utf-16" | A collection of UTF-16 code units |
"unicode-scalars" | A collection of Unicode scalars (the same as UTF-32), or one Unicode scalar |
With no format, a number that cannot be a code point (NaN, an infinity, a
number that is not an integer, a negative number, a complex number) is
printed, as is any value that is not a number: a string, a boolean, a
symbol, an expression. To print an integer instead of decoding it, give the
"default" format.
[stringFrom(128287), stringFrom([127467, 127479])]
// ➔ ["🔟","🇫🇷"]
stringFrom(128287, "default")
// ➔ "128287"
[stringFrom(-1), stringFrom(1.5), stringFrom(NaN)]
// ➔ ["-1","1.5","NaN"]
A tuple of numbers is not decoded, because a tuple holds the coordinates
of a point. Use a list, or give the "unicode-scalars" format.
stringFrom((65, 66))
// ➔ "(65, 66)"
stringFrom((65, 66), "unicode-scalars")
// ➔ "AB"
The three encoding formats take a collection of integers (or, for
"unicode-scalars", one integer). A string argument is an error: a string
is a collection of characters, not of code units. Convert it first with
utf8, utf16 or unicodeScalars.
stringFrom([72, 101, 108, 108, 111], "utf-8")
// ➔ "Hello"
stringFrom([55357, 56607], "utf-16")
// ➔ "🔟"
stringFrom("abc", "utf-8")
// ➔ error: Runtime error: expected `indexed_collection<integer>`, got `string`
MathJSON: StringFrom
["StringFrom", value], ["StringFrom", value, format].
["StringFrom", 128287]
// ➔ "🔟"
["StringFrom", ["List", 127467, 127479]]
// ➔ "🇫🇷"
["StringFrom", 128287, {str: "default"}]
// ➔ "128287"
["StringFrom", ["List", 72, 101, 108, 108, 111], {str: "utf-8"}]
// ➔ "Hello"
stringJoin
(collection<character | string>, separator: (character | string)?) -> string
- argument 1 — The finite collection of strings or characters to join; an empty collection gives
"". Sample:["a", "b", "c"]. separator— The text placed between consecutive elements; by default, none. Sample:"-".
StringJoin(xs): join the elements of the finite collection xs (strings or characters) into a string.
StringJoin(xs, sep): the same, with sep between consecutive elements. The inverse of StringSplit. An empty collection joins to "", a one-element collection to that element. A non-text element, or a non-finite collection, leaves the expression unevaluated. For variadic concatenation use Join(a, b, …) or string interpolation.
stringJoin(["a", "b", "c"], "-")
// ➔ "a-b-c"
stringJoin is the inverse of stringSplit, and does what
Python's separator.join(parts) does.
stringJoin(["a", "b", "c"], ", ")
// ➔ "a, b, c"
[stringJoin([]), stringJoin(["a"]), stringJoin(characters("abc"))]
// ➔ ["","a","abc"]
Unlike String, which converts any argument to text,
stringJoin is strict: an element that is neither a string nor a character
is a type error when the type of the collection shows it. A collection that
is not finite leaves the expression unevaluated.
stringJoin(["a", 1])
// ➔ error: Type error: expected `collection<character | string>`, got `list<integer | string>` at `["a", 1]` in `stringJoin(["a", 1])`
stringJoin(repeat("a"))
// ➔ StringJoin(Repeat("a"))
A string is the collection of its characters, so joining a string with a
separator puts the separator between its characters, as Python's
sep.join(s) does. A character is not a collection: put it in a list, or
use String.
stringJoin("abc", "-")
// ➔ "a-b-c"
stringJoin(characterFrom("a"))
// ➔ error: Type error: expected `collection<character | string>`, got `character` at `characterFrom("a")` in `stringJoin(characterFrom("a"))`
Migrating from the variadic stringJoin
stringJoin used to take any number of strings and concatenate them:
stringJoin("ab", "cd") was "abcd". It now takes one collection, and the
same call is still accepted with another meaning: the characters of "ab"
joined with the separator "cd". There is no error, only a different
result, so check every call of stringJoin with more than one argument.
stringJoin("ab", "cd")
// ➔ "acdb"
To concatenate a fixed number of strings, use
join or string interpolation, and keep
stringJoin for a collection to join.
let a = "ab"
let b = "cd"
[join(a, b), "\(a)\(b)"]
// ➔ ["abcd","abcd"]
MathJSON: StringJoin • LaTeX: \lt\gt
["StringJoin", xs], ["StringJoin", xs, separator].
["StringJoin", ["List", {str: "a"}, {str: "b"}, {str: "c"}], {str: ", "}]
// ➔ "a, b, c"
["StringJoin", ["List"]]
// ➔ ""
["StringJoin", {str: "abc"}, {str: "-"}]
// ➔ "a-b-c"
stringRepeat
(character | string, n: integer) -> string
- argument 1 — The string to repeat. Sample:
"ab". n— The number of copies, a non-negative integer; 0 gives"". Sample:3.
StringRepeat(s, n): n copies of the string s, concatenated. StringRepeat(s, 0) is "". A negative or non-integer n is an error.
stringRepeat("ab", 3)
// ➔ "ababab"
The count must be a non-negative integer: a negative count is an error, and a count that is not an integer is a type error. Like every concatenation, the result is segmented again, so repeating a lone combining mark does not multiply the number of characters.
stringRepeat("ab", 0)
// ➔ ""
stringRepeat("ab", -1)
// ➔ error: Runtime error: unexpected argument
length(stringRepeat("\u{301}", 3))
// ➔ 1
The name is stringRepeat, not repeat, because
repeat makes an infinite collection.
MathJSON: StringRepeat
["StringRepeat", s, n].
["StringRepeat", {str: "ab"}, 3]
// ➔ "ababab"
stringReplace
((character | string, character | string, character | string, count: integer?) -> string) & ((character | string, regexp, character | string, count: integer?) -> string) & ((character | string, regexp, function, count: integer?) -> string)
- argument 1 — The string in which to replace. Sample:
"banana". - argument 2 — The text to find, which must not be empty, or a regular expression. Sample:
"a". - argument 3 — The replacement text, empty to delete, or, with a regular expression, a function of the match record that returns it. Sample:
"o". count— The largest number of occurrences to replace, from the left, a positive integer; by default, all of them. Sample:1.
StringReplace(s, target, replacement): replace every non-overlapping occurrence of target in s, scanning left to right over whole characters.
StringReplace(s, target, replacement, count): replace at most count occurrences, from the left. An empty target is an error (the "insert at every boundary" behavior is deliberately not inherited); an empty replacement means deletion. count must be a positive integer.
StringReplace(s, pattern, replacement, count?): target may be a regular expression, matched with the host dialect. $1-style templates are NOT expanded in replacement.
StringReplace(s, pattern, f, count?): replacement may be a function, called with the same match record StringMatch returns, so each replacement can be computed from its captures.
stringReplace("banana", "a", "o")
// ➔ "bonono"
stringReplace("banana", "a", "o", 1)
// ➔ "bonana"
The occurrences of the target are found as rangeOf
finds them, character by character, from left to right and without overlap.
The search moves past each match in the original string, so the text of a
replacement is never matched again.
stringReplace("banana", "na", "")
// ➔ "ba"
stringReplace("aa", "a", "aa")
// ➔ "aaaa"
A target cannot match part of a character:
stringReplace("x\u{301}y", "x", "z")
// ➔ "x́y"
Every occurrence is replaced, unless a count limits the replacements, from
the left; the count must be a positive integer. An empty target is an error:
inserting the replacement at every boundary, as the host's
replaceAll("", x) does, is not done. An empty replacement deletes the
target. When the string is not a string, such as a symbol with no value, the
expression stays unevaluated.
stringReplace("a-b-c", "-", "+", 1)
// ➔ "a+b-c"
stringReplace("abc", "", "x")
// ➔ error: Runtime error: unexpected argument
stringReplace("abc", "a", "x", 0)
// ➔ error: Runtime error: unexpected argument
stringReplace(x, "a", "b")
// ➔ StringReplace(x, "a", "b")
A string target is always a literal sequence of characters. To replace the matches of a regular expression, or to compute each replacement with a function, see Patterns with stringSplit and stringReplace.
MathJSON: StringReplace
["StringReplace", s, target, replacement],
["StringReplace", s, target, replacement, count].
["StringReplace", {str: "a-b-c"}, {str: "-"}, {str: "+"}]
// ➔ "a+b+c"
["StringReplace", {str: "a-b-c"}, {str: "-"}, {str: "+"}, 1]
// ➔ "a+b-c"
stringSplit
((character | string, (character | string)?) -> list<string>) & ((character | string, regexp) -> list<string>)
- argument 1 — The string to split. Sample:
"a,b,c". - argument 2 — The separator string, with the empty parts kept, or a regular expression; an empty separator splits into characters, and by default the split is on runs of whitespace. Sample:
",".
StringSplit(s): split a string on runs of whitespace (the Unicode White_Space code points), dropping empty parts.
StringSplit(s, sep): split a string on the separator string sep (empty parts are kept). An empty separator splits into user-perceived characters (grapheme clusters), like Characters. A non-string argument leaves the expression unevaluated.
StringSplit(s, pattern): split on each match of a regular expression, with the host dialect's own semantics — including splitting at a zero-width match. Captures are not interleaved into the result; use StringMatchAll for those.
stringSplit("a,b,c", ",")
// ➔ ["a","b","c"]
stringSplit(" one two three ")
// ➔ ["one","two","three"]
With no separator, the string is split on runs of whitespace and empty parts
are dropped. Whitespace is the code points with the Unicode White_Space
property (U+0009 to U+000D, U+0020, U+0085, U+00A0, U+1680, U+2000 to
U+200A, U+2028, U+2029, U+202F, U+205F, U+3000), whatever the host's \s
matches.
stringSplit("the quick brown fox")
// ➔ ["the","quick","brown","fox"]
stringSplit("a\u{a0}b\tc")
// ➔ ["a","b","c"]
With a separator, the string is split at each occurrence of the separator, and empty parts are kept.
stringSplit("a,b,,c", ",")
// ➔ ["a","b","","c"]
An empty separator splits into grapheme clusters, as
characters does, but the parts are one-character
strings, not characters. To split into characters, use characters, or
iterate or index the string.
stringSplit("abc", "")
// ➔ ["a","b","c"]
type(stringSplit("abc", "")[1])
// ➔ TypeFrom("string")
To split on the matches of a regular expression, see Patterns with stringSplit and stringReplace.
MathJSON: StringSplit
["StringSplit", s], ["StringSplit", s, separator].
["StringSplit", {str: "the quick brown fox"}]
// ➔ ["List", "'the'", "'quick'", "'brown'", "'fox'"]
["StringSplit", {str: "a,b,,c"}, {str: ","}]
// ➔ ["List", "'a'", "'b'", "''", "'c'"]
Subscript
(collection<any>, any) -> any
Subscript notation for indexing or compound symbols.
Subscript([10, 20, 30], 2)
// ➔ 20
The way LaTeX subscripts are read, as part of a name, as an index or as an expression, is described in Subscripts and superscripts.
MathJSON: Subscript • LaTeX: _
Subtype
(subtype: string | type, supertype: string | type) -> boolean
True iff the FIRST operand is a subtype of the second — Subtype("integer", "number") is True, Subtype("number", "integer") is False. This is the same compatibility relation annotations and signatures use. Operands are type values or type text; a quantified (where) type is not comparable and errors.
Subtype("integer", "number")
// ➔ true
symbol
function
Construct a new symbol with a name formed by concatenating the arguments
symbol("x", 2)
// ➔ x2
The symbol is not declared: it is a free variable.
symbol(x, 2)
// ➔ x2
MathJSON: Symbol
["Symbol", expr1, expr2, ...]. To declare it, use Declare with a value:
["Declare", ["Symbol", "x", 2], "real", 0].
tail
(any) -> collection
- argument 1 — The expression whose operands are returned; an expression with no operands gives
Nothing. Sample:max(a, b, c).
Return the tail of an expression, the operands of the expression
[tail(max(a, b, c))]
// ➔ [a,b,c]
tail is a sequence, so in a list or a call its elements are spliced in. A
symbol is read through its value; a symbol with no value, or any value that
is not a compound expression, has no tail, and tail gives nothing.
tail(2 + x)
// ➔ 2 x
let x = a + 1
[tail(x), tail(y)]
// ➔ [a,1,nothing]
MathJSON: Tail
["Tail", expr] is a Sequence, so it can change the head of an expression:
["Multiply", ["Tail", ["Add", 2, 3]]]
// ➔ ["Multiply", 2, 3]
Text
(any*) -> string
A sequence of strings, annotated expressions and other Text expressions
Text("Total: ", 42)
// ➔ "Total: 42"
timing
MathJSON Timing · (value, repeat: integer?) -> tuple<number, value>
- argument 1 — The expression to evaluate and time. Sample:
2 + 2. repeat— The number of evaluations; a count below 3 counts as 3, and the fastest and the slowest are dropped from the mean. Sample:10.
timing(expr) evaluates expr and returns a pair: the time the evaluation took, in microseconds, then the value; read them as timing(expr)[1] and timing(expr)[2]. timing(expr, n) evaluates expr n times (at least 3), drops the fastest and the slowest run, and returns the mean time of the others
timing(2 + 2)[2]
// ➔ 4
to
(any, any) -> nothing
- argument 1 — The left side of the arrow. Sample:
x. - argument 2 — The right side of the arrow. Sample:
3.
Action arrow / mapping (a \to b) — opaque typed head.
replaceAll(x^2 + x, to(x, 3))
// ➔ 12
MathJSON: To • LaTeX: \to
toLowerCase
MathJSON ToLowerCase · (character | string) -> string
- argument 1 — The string to convert. Sample:
"Hello World".
ToLowerCase(s): the string s mapped to lower case using the Unicode default (locale-independent) mappings.
toLowerCase("Hello World")
// ➔ "hello world"
toUpperCase
(character | string) -> string
- argument 1 — The string to convert. Sample:
"straße".
ToUpperCase(s): the string s mapped to upper case using the Unicode default (locale-independent) mappings. The character count can change ("ß" uppercases to "SS").
toUpperCase("straße")
// ➔ "STRASSE"
toUpperCase and toLowerCase map the whole string, not each character on
its own, because case mapping depends on the context:
- The number of characters can change. The German
ßis two characters in upper case. - The Greek final sigma depends on its position. A
Σat the end of a word isςin lower case, notσ.
[length("straße"), length(toUpperCase("straße"))]
// ➔ [6,7]
toLowerCase("ΟΔΟΣ")
// ➔ "οδος"
There is no locale argument, so the Turkish dotless i is not available:
toLowerCase("I") is "i" on every host, which keeps canonical forms and
keys the same everywhere. To compare strings without regard to case, use
caseFold, not toLowerCase.
toLowerCase("I")
// ➔ "i"
MathJSON: ToUpperCase
["ToUpperCase", s], ["ToLowerCase", s].
["ToUpperCase", {str: "hello"}]
// ➔ "HELLO"
["ToLowerCase", {str: "HELLO"}]
// ➔ "hello"
triangle
(any+) -> expression
- arguments 1, … — A vertex of the triangle. Sample:
A.
Triangle primitive — opaque typed head.
triangle(A, B, C)
// ➔ Triangle(A, B, C)
MathJSON: Triangle • LaTeX: \operatorname{triangle}
trim
(character | string, chars: (character | collection<character | string> | string)?) -> string
- argument 1 — The string to trim. Sample:
" hi ". chars— The characters to remove at both ends, as a character, a string or a collection of them; by default, whitespace. Sample:"-".
Trim(s): remove leading and trailing whitespace (the Unicode White_Space characters).
Trim(s, chars): remove leading and trailing characters that belong to chars — a SET of characters, given as a character, a string (meaning the set of that string's characters) or a collection whose elements each contribute their own characters.
trim(" hi ")
// ➔ "hi"
trim("--hi--", "-")
// ➔ "hi"
trim removes characters at both ends, trimStart at the start only and
trimEnd at the end only. With no second argument, they remove the Unicode
White_Space characters, as stringSplit defines them.
[trim(" hi "), trimStart(" hi "), trimEnd(" hi ")]
// ➔ ["hi","hi "," hi"]
trim("\u{a0}hi\u{3000}")
// ➔ "hi"
The second argument is a set of characters to remove, not a prefix or a suffix. A string stands for the set of its characters.
trim("abcba", "ab")
// ➔ "c"
trim("--hi..", ["-", "."])
// ➔ "hi"
To remove a literal prefix or suffix, test it with
startsWith or
endsWith, and
drop it.
MathJSON: Trim
["Trim", s], ["Trim", s, chars], and likewise TrimStart and TrimEnd.
["Trim", {str: "xxhixx"}, {str: "x"}]
// ➔ "hi"
trimEnd
MathJSON TrimEnd · (character | string, chars: (character | collection<character | string> | string)?) -> string
- argument 1 — The string to trim. Sample:
" hi ". chars— The characters to remove at the end, as a character, a string or a collection of them; by default, whitespace. Sample:"-".
TrimEnd(s): remove trailing whitespace (the Unicode White_Space characters).
TrimEnd(s, chars): remove trailing characters that belong to chars — a SET of characters, as for Trim.
trimEnd("hi!!", "!")
// ➔ "hi"
trimStart
MathJSON TrimStart · (character | string, chars: (character | collection<character | string> | string)?) -> string
- argument 1 — The string to trim. Sample:
" hi ". chars— The characters to remove at the start, as a character, a string or a collection of them; by default, whitespace. Sample:"-".
TrimStart(s): remove leading whitespace (the Unicode White_Space characters).
TrimStart(s, chars): remove leading characters that belong to chars — a SET of characters, as for Trim.
trimStart("007", "0")
// ➔ "7"
type
(any) -> type
- argument 1 — The expression whose static type is returned; it is not evaluated. Sample:
[1, 2, 3].
The STATIC type of an expression, as a type value: type("hi") is TypeFrom("string"). The observer does not evaluate its operand, except a name with no declared type, which gives the widened type of the value it holds. Recover the text with stringFrom(type(x)); in a string interpolation a type value renders as its text directly. BREAKING (2026-08-19, ruling R3 of docs/TYPE-SYSTEM.md): the result used to be a STRING, and type(x) == "some text" is now always False — use x is T, Subtype(type(x), u), or compare stringFrom text.
type("hi")
// ➔ TypeFrom("string")
type([1, 2, 3])
// ➔ TypeFrom("vector<integer^3>")
The result is the literal type of the expression, the most precise type
of its value: the type of 2.4531 is 2.4531, which widens to real, a
finite real. A name with a declared type gives that type. A name with no
declared type, such as an untyped parameter, gives the type of its value,
widened.
type(2.4531)
// ➔ TypeFrom("2.4531")
function f(x) { type(x) }
f(1)
// ➔ TypeFrom("integer")
See Types.
MathJSON: Type
["Type", expr].
["Type", 2.4531]
// ➔ ["TypeFrom", "'2.4531'"]
typeFrom
MathJSON TypeFrom · (text: string) -> type
text— The text of the type; an unknown type name is an error. Sample:"list<integer>".
A type expression as a first-class value, constructed from its text: TypeFrom("list<integer>"). The value SETTLES at construction — the text is parsed, reduced, and stored back as its canonical form — so two values built from equivalent spellings ("integer|real", "real|integer") are the same value. == between two type values is mutual subtyping (it also equates an alias with its body); == between a type value and anything else, a string included, is False. Construction never touches the type registry: a forward reference (type X) or an unknown name is an error, not a registration.
TypeFrom("integer | real") == TypeFrom("real")
// ➔ true
Typed
(any, string | symbol) -> unknown
Ascribe a type to an expression. The type is asserted for the type system. At evaluation, a concrete value that does not conform to the type is an incompatible-type error; any other value is returned unchanged. Used to annotate Function literal parameters and return types.
Typed(2 + 3, "integer")
// ➔ 5
Typed(expr, type) sets the static type of the expression. When it is
evaluated, a concrete value (a number, a string, a character, a boolean, or a
list or tuple of these) is checked against the type, and a value that does
not conform is an incompatible-type error. A symbolic value, missing,
nothing, NaN and an error pass unchanged. A float conforms to every type
that admits a real number, so the value of N passes under integer. A
character conforms where a string is declared.
Typed(2 + 3, integer)
// ➔ 5
Typed("s", integer)
// ➔ error: Runtime error: expected `integer`, got `string` at `s`
MathJSON: Typed
["Typed", expr, type], with the type as a string or a type name. Its main
use is to annotate the parameters and the result of a
function literal.
Unevaluated
(any) -> unknown
Prevent an expression from being evaluated
unicodeScalars
(character | string) -> list<integer>
- argument 1 — The string to decompose. Sample:
"A😀".
A collection of Unicode scalars from a string, same as UTF-32
unicodeScalars("A😀")
// ➔ [65,128512]
A Unicode scalar is a Unicode code point from U+0000 to U+10FFFF, except the surrogates U+D800 to U+DFFF. Unicode scalars are the code units of UTF-32.
A character can be several scalars: the emoji 👩🎓 is one character and
three scalars. The scalars are those of the NFC form of the string, so a
decomposed é gives the one scalar of the precomposed form. To make a
string from Unicode scalars, use stringFrom.
unicodeScalars("👩🎓")
// ➔ [128105,8205,127891]
[unicodeScalars("é"), unicodeScalars("e\u{301}")]
// ➔ [[233],[233]]
stringFrom(unicodeScalars("👩🎓"))
// ➔ "👩🎓"
See also utf8, utf16 and
characters.
MathJSON: UnicodeScalars
["UnicodeScalars", s].
["UnicodeScalars", {str: "👩🎓"}]
// ➔ ["List", 128105, 8205, 127891]
utf16
(character | string) -> list<integer>
- argument 1 — The string to encode. Sample:
"A😀".
A collection of UTF-16 code units from a string.
utf16("A😀")
// ➔ [65,55357,56832]
The values are UTF-16 code units, not Unicode scalars: a scalar above
U+FFFF is two code units. To make a string from UTF-16 code units, use
stringFrom(units, "utf-16").
utf16("👩🎓")
// ➔ [55357,56425,8205,55356,57235]
stringFrom(utf16("👩🎓"), "utf-16")
// ➔ "👩🎓"
See also utf8, unicodeScalars and
characters.
MathJSON: Utf16
["Utf16", s].
["Utf16", {str: "Hello"}]
// ➔ ["List", 72, 101, 108, 108, 111]
utf8
(character | string) -> list<integer>
- argument 1 — The string to encode. Sample:
"A€".
A collection of UTF-8 code units from a string.
utf8("A€")
// ➔ [65,226,130,172]
The values are UTF-8 bytes, not Unicode scalars. To make a string from
UTF-8 bytes, use stringFrom(bytes, "utf-8").
utf8("👩🎓")
// ➔ [240,159,145,169,226,128,141,240,159,142,147]
stringFrom(utf8("👩🎓"), "utf-8")
// ➔ "👩🎓"
See also utf16, unicodeScalars and
characters.
MathJSON: Utf8
["Utf8", s].
["Utf8", {str: "Hello"}]
// ➔ ["List", 72, 101, 108, 108, 111]
Wildcard
(symbol) -> symbol
Single-expression pattern wildcard.
Wildcard(x)
// ➔ _x
WildcardOptionalSequence
(symbol) -> symbol
Pattern wildcard matching zero or more expressions.
WildcardOptionalSequence(x)
// ➔ ___x
WildcardSequence
(symbol) -> symbol
Pattern wildcard matching one or more expressions.
WildcardSequence(x)
// ➔ __x
withRandomSeed
(seed: real | string, body: any) -> expression
seed— The seed: a finite real or a string; the same seed gives the same draws. Sample:42.body— The expression to evaluate, held until the seed frame exists. Sample:random(1..6).
WithRandomSeed(seed, body): evaluate body with a random seed frame seeded by seed (a finite real or a string). The block replays identically, while repeated draws WITHIN the frame differ (the n-th draw is hash(seed, n)).
Scoping is dynamic: the frame is active through user-function calls, not just lexically inside body. Frames nest and the innermost wins.
Counters are per-frame, so a nested frame does not perturb its parent's subsequent draws.
Outside any frame, draws are live (non-deterministic).
withRandomSeed(42, [random(1..6), random(1..6), random(1..6)])
// ➔ [5,3,5]
The seed must be a finite real number or a string. An infinite or undefined
seed is an out-of-range error. The seed is evaluated once, when the block
starts.
[withRandomSeed(42, random()), withRandomSeed(42, random())]
// ➔ [0.7367300395263549,0.7367300395263549]
withRandomSeed(42, [random(), random()])
// ➔ [0.7367300395263549,0.4498528692283148]
withRandomSeed(oo, random())
// ➔ error: Runtime error: out of range: a finite real number or a string, +oo
Blocks nest, and the innermost wins. Each block counts its own draws, so a
nested block does not change the later draws of the block around it: below,
the first and third values are the first two values of the block seeded with
1.
withRandomSeed(1, [random(), withRandomSeed(2, random()), random()])
// ➔ [0.9834569781146947,0.43120335189750414,0.20647662186831073]
Seed a row or a cell, not a whole document: with one block around a whole document, a draw added near the top changes every value below it.
A block around a lazy collection does not make it replay. Only evaluation
draws, and a lazy collection is not evaluated until its elements are read.
By then the block has ended, so the draws are not seeded. The expression
looks seeded, and nothing reports the problem. Make the list inside the
block, with listFrom, and it replays:
let a = withRandomSeed(3, [random() for k in 1..3])
let b = withRandomSeed(3, [random() for k in 1..3])
a[1] == b[1]
// ➔ false
let a = withRandomSeed(3, listFrom([random() for k in 1..3]))
let b = withRandomSeed(3, listFrom([random() for k in 1..3]))
a[1] == b[1]
// ➔ true
Reading the elements of the same lazy collection twice gives the same values: the elements of one collection are cached. That is consistent reading, not replay: the values are unseeded draws, and a new collection draws new ones.
repeat(random(), n) draws a new value for each element: a value that is
not pure is evaluated once per element (see
repeat).
let r = repeat(random(), 3)
r[1] == r[2]
// ➔ false
MathJSON: WithRandomSeed
["WithRandomSeed", seed, body]. A string seed is a MathJSON string,
"'cell-a7'".
["WithRandomSeed", 42, ["Random"]]
// ➔ 0.7367300395263549
["WithRandomSeed", "PositiveInfinity", ["Random"]]
// ➔ ["Error", ["ErrorCode", "'out-of-range'", "'a finite real number or a string'", "'+oo'"]]