Compute Engine API Reference
module compute-engineClasses
interface BoxedBaseDefinition Permalink
Extended by BoxedSymbolDefinition
interface BoxedBaseDefinitionProperties / Methods
interface BoxedBaseDefinitiondescription Permalink
- | string
- | string[]
interface BoxedBaseDefinitionname: string Permalink
interface BoxedBaseDefinitionreset() Permalink
When the environment changes, for example the numerical precision,
call reset()
so that any cached values can be recalculated.
interface BoxedBaseDefinitionscope: undefined | RuntimeScope Permalink
The scope this definition belongs to.
This field is usually undefined, but its value is set by getDefinition()
interface BoxedBaseDefinitionurl: string Permalink
interface BoxedBaseDefinitionwikidata: string Permalink
interface BoxedDomain Permalink
Extends BoxedExpression
interface BoxedDomainProperties / Methods
Dictionary Expression
Domain Properties
Expression Properties
Function Expression
Numeric Expression
String Expression
Symbol Expression
Other
Primitive Methods
Relational Operator
Dictionary Expression
Domain Properties
Expression Properties
Function Expression
Numeric Expression
String Expression
Symbol Expression
Other
interface BoxedDomainisCompatible() Permalink
True if a valid domain, and compatible with dom
kind
is ‘“covariant”’ by default, i.e. this <: dom
interface BoxedDomainisFunction: boolean Permalink
interface BoxedDomainisNumeric: boolean Permalink
interface BoxedDomainbase: DomainLiteral read only Permalink
interface BoxedDomaincanonical: BoxedDomain read only Permalink
interface BoxedDomainctor: null | DomainConstructor read only Permalink
interface BoxedDomainjson: Expression read only Permalink
interface BoxedDomainparams: DomainExpression<SemiBoxedExpression>[] read only Permalink
Primitive Methods
Relational Operator
interface BoxedExpression Permalink
Extended by BoxedDomain, Pattern
THEORY OF OPERATIONS
The BoxedExpression
interface includes most of the member functions
applicable to any kind of expression, for example get symbol()
or
get ops()
.
When a member function is not applicable to this BoxedExpression
,
for example get symbol()
on a BoxedNumber
, it returns null
.
This convention makes it convenient to manipulate expressions without having to check what kind of instance they are before manipulating them.
interface BoxedExpressionProperties / Methods
Dictionary Expression
Domain Properties
Expression Properties
Function Expression
Numeric Expression
String Expression
Symbol Expression
Other
Primitive Methods
Relational Operator
Dictionary Expression
interface BoxedExpressiongetKey() Permalink
If this expression is a dictionary, return the value of the key
entry.
interface BoxedExpressionhasKey() Permalink
If this expression is a dictionary, return true if the
dictionary has a key
entry.
interface BoxedExpressionkeys Permalink
- | null
- | IterableIterator<string>
The keys of the dictionary.
If this expression not a dictionary, return null
interface BoxedExpressionkeysCount: number Permalink
Domain Properties
interface BoxedExpressionisAlgebraic: undefined | boolean Permalink
The value of this expression is a number that is the root of a non-zero univariate polynomial with rational coefficients.
All integers and rational numbers are algebraic.
Transcendental numbers, such as \( \pi \) or \( e \) are not algebraic.
interface BoxedExpressionisComplex: undefined | boolean Permalink
The value of this expression is a number, but not NaN
or any Infinity
isReal || isImaginary
interface BoxedExpressionisExtendedComplex: undefined | boolean Permalink
isReal || isImaginary || isInfinity
interface BoxedExpressionisExtendedReal: undefined | boolean Permalink
Real or ±Infinity
isReal || isInfinity
interface BoxedExpressionisImaginary: undefined | boolean Permalink
The value of this expression is a number with a imaginary part
interface BoxedExpressionisInteger: undefined | boolean Permalink
The value of this expression is an element of the set ℤ: …,-2, -1, 0, 1, 2…
interface BoxedExpressionisNumber: undefined | boolean Permalink
true
if the value of this expression is a number.
isExtendedComplex || isNaN
= isReal || isImaginary || isInfinity || isNaN
Note that in a fateful twist of cosmic irony, NaN
(“Not a Number”)
is a number.
interface BoxedExpressionisRational: undefined | boolean Permalink
The value of this expression is an element of the set ℚ, p/q with p ∈ ℕ, q ∈ ℤ ⃰ q >= 1
Note that every integer is also a rational.
interface BoxedExpressionisReal: undefined | boolean Permalink
The value of this expression is real number: finite and not imaginary.
isFinite && !isImaginary
Expression Properties
interface BoxedExpressionisComposite: undefined | boolean Permalink
interface BoxedExpressionisEven: undefined | boolean Permalink
interface BoxedExpressionisFinite: undefined | boolean Permalink
This expression is a number, but not ±Infinity and not NaN
interface BoxedExpressionisInfinity: undefined | boolean Permalink
The numeric value of this expression is ±Infinity or Complex Infinity
interface BoxedExpressionisNaN: undefined | boolean Permalink
“Not a Number”.
A value representing undefined result of computations, such as 0/0
,
as per the floating point format standard IEEE-754.
Note that if isNaN
is true, isNumber
is also true (yes, NaN
is a
number).
interface BoxedExpressionisNegative: undefined | boolean Permalink
The numeric value of this expression is < 0, same as isLess(0)
interface BoxedExpressionisNegativeOne: undefined | boolean Permalink
The numeric value of this expression is not -1.
interface BoxedExpressionisNonNegative: undefined | boolean Permalink
The numeric value of this expression is >= 0, same as isGreaterEqual(0)
interface BoxedExpressionisNonPositive: undefined | boolean Permalink
The numeric value of this expression is <= 0, same as isLessEqual(0)
interface BoxedExpressionisNotZero: undefined | boolean Permalink
The numeric value of this expression is not 0.
interface BoxedExpressionisOdd: undefined | boolean Permalink
interface BoxedExpressionisOne: undefined | boolean Permalink
The numeric value of this expression is not 1.
interface BoxedExpressionisPositive: undefined | boolean Permalink
The numeric value of this expression is > 0, same as isGreater(0)
interface BoxedExpressionisPrime: undefined | boolean Permalink
interface BoxedExpressionisZero: undefined | boolean Permalink
The numeric value of this expression is 0.
Function Expression
interface BoxedExpressionnops: number Permalink
If this expression is a function, the number of operands, otherwise 0.
Note that a function can have 0 operands, so to check if this expression
is a function, check if this.ops !== null
instead.
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionop1: BoxedExpression Permalink
First operand, i.e.this.ops[0]
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionop2: BoxedExpression Permalink
Second operand, i.e.this.ops[1]
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionop3: BoxedExpression Permalink
Third operand, i.e. this.ops[2]
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionops Permalink
- | null
- | BoxedExpression[]
The list of arguments of the function, its “tail”.
If the expression is not a function, return null
.
Note applicable to canonical and non-canonical expressions.
Numeric Expression
interface BoxedExpressionnumericValue Permalink
- | null
- | number
- | Decimal
- | Complex
- | Rational
Return the value of this expression, if a number literal.
Note it is possible for numericValue
to be null
, and for isNotZero
to be true. For example, when a symbol has been defined with an assumption.
Conversely, isNumber
may be true even if numericValue
is null
,
example the symbol Pi
return true for isNumber
but numericValue
is
null
. It’s value can be accessed with .value.numericValue
interface BoxedExpressionsgn Permalink
- | undefined
- | null
- | 0
- | 1
- | -1
Return the following, depending on the value of this expression:
-1
if it is < 00
if it is = 0+1
if it is > 0undefined
this value may be positive, negative or zero. We don’t know right now (a symbol with an Integer domain, but no currently assigned value, for example)null
this value will never be positive, negative or zero (NaN
, a string or a complex number for example)
Note that complex numbers have no natural ordering,
so if the value is a complex number, sgn
is either 0, or null
If a symbol, this does take assumptions into account, that is this.sgn
will return 1
if isPositive
is true
, even if this expression has
no value
String Expression
interface BoxedExpressionstring: null | string Permalink
If this expression is a string, return the value of the string.
Otherwise, return null
.
Note applicable to canonical and non-canonical expressions.
Symbol Expression
interface BoxedExpressionisValid: boolean Permalink
true
if this expression or any of its subexpressions is an ["Error"]
expression.
Note applicable to canonical and non-canonical expressions. For non-canonical expression, this may indicate a syntax error while parsing LaTeX. For canonical expression, this may indicate argument domain mismatch, or missing or unexpected arguments.
interface BoxedExpressionsymbol: null | string Permalink
If this expression is a symbol, return the name of the symbol as a string.
Otherwise, return null
.
Note applicable to canonical and non-canonical expressions.
Other
interface BoxedExpressionN() Permalink
Return a numeric approximation of the canonical form of this expression.
Any necessary calculations, including on decimal numbers (non-integers), are performed.
The calculations are performed according to the numericMode
and
precision
properties of the ComputeEngine
.
To only perform exact calculations, use this.evaluate()
instead.
If the function is not numeric, the result of this.N()
is the same as
this.evaluate()
.
The result is in canonical form.
interface BoxedExpressionbaseDefinition: undefined | BoxedBaseDefinition Permalink
For symbols and functions, a possible definition associated with the
expression. baseDefinition
is the base class of symbol and function
definition.
Note undefined
if not a canonical expression.
interface BoxedExpressioncompile() Permalink
- to?: "javascript"
-
options?:
- optimize: ("simplify" | "evaluate")[];
- → undefined | (args: Record<string, any>): any
interface BoxedExpressioncomplexity: undefined | number Permalink
Expressions with a higher complexity score are sorted first in commutative functions
Note undefined
if not a canonical expression.
interface BoxedExpressiondescription Permalink
- | undefined
- | string[]
An optional short description if a symbol or function expression.
May include markdown. Each string is a paragraph.
Note undefined
if not a canonical expression.
interface BoxedExpressionengine: IComputeEngine Permalink
The Compute Engine associated with this expression provides a context in which to interpret it, such as definition of symbols and functions.
ComputeEngine is the class that implements IComputeEngine.
interface BoxedExpressionerrors: BoxedExpression[] Permalink
All the ["Error"]
subexpressions
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionevaluate() Permalink
Return the value of the canonical form of this expression.
A pure expression always return the same value and has no side effects.
If expr.isPure
is true
, expr.value
and expr.evaluate()
are
synonyms.
For an impure expression, expr.value
is undefined.
Evaluating an impure expression may have some side effects, for
example modifying the ComputeEngine
environment, such as its set of
assumptions.
Only exact calculations are performed, no approximate calculations on decimal numbers (non-integer numbers). Constants, rational numbers and square root of rational numbers are preserved.
To perform approximate calculations, use expr.N()
instead.
The result of expr.evaluate()
may be the same as expr.simplify()
.
The result is in canonical form.
interface BoxedExpressionfreeVariables: string[] Permalink
All the identifiers (symbols and functions) in the expression that are not a local variable or a parameter of that function.
interface BoxedExpressionfunctionDefinition: undefined | BoxedFunctionDefinition Permalink
For functions, a possible definition associated with the expression.
Note undefined
if not a canonical expression or not a function.
interface BoxedExpressiongetSubexpressions() Permalink
All the subexpressions matching the head
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionhas() Permalink
True if the expression includes a symbol v
or a function head v
.
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionhead: string | BoxedExpression Permalink
All boxed expressions have a head.
If not a function this can be Symbol
, String
, Number
or Dictionary
.
If the head expression can be represented as a string, it is returned as a string.
Note applicable to canonical and non-canonical expressions. The head
of a non-canonical expression may be different than the head of its
canonical counterpart. For example the canonical counterpart of ["Divide", 5, 7]
is ["Rational", 5, 5]
.
interface BoxedExpressionisConstant: boolean Permalink
True if the expression is a constant, that is a symbol with an immutable value
interface BoxedExpressionisExact: boolean Permalink
An exact value is not further transformed when evaluated. To get an
approximate evaluation of an exact value, use .N()
.
Exact numbers are:
- rationals (including integers)
- complex numbers with integer real and imaginary parts (Gaussian integers)
- square root of rationals
Non-exact values includes:
- numbers with a fractional part
- complex numbers with a real or imaginary fractional part
interface BoxedExpressionisNothing: boolean Permalink
If this is the Nothing
symbol, return true
.
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionisPure: boolean Permalink
If true, the value of the expression never changes and evaluating it has no side-effects. If false, the value of the expression may change, if the value of other expression changes or for other reasons.
If this.isPure
is false
, this.value
is undefined. Call
this.evaluate()
to determine the value of the expression instead.
As an example, the Random
function is not pure.
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionjson: Expression Permalink
MathJSON representation of this expression.
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionmatch() Permalink
Attempt to match this expression to the rhs
expression.
If rhs
does not match, return null
.
Otherwise return an object literal.
If this expression includes wildcards (symbols with a name that starts
with _
), the object literal will include a prop for each matching named
wildcard.
If rhs
matches this pattern but there are no named wildcards, return
the empty object literal, {}
.
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionrank: number Permalink
Return 0 for a scalar, 1 for a vector, 2 for a matrix, > 2 for a multidimensional matrix. It’s the length of expr.shape
interface BoxedExpressionreplace() Permalink
Transform the expression by applying the rules:
if the lhs
of a rule matches, it is replaced by its rhs
.
If no rules apply, return null
.
See also subs
for a simple substitution.
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionscope: null | RuntimeScope Permalink
The scope in which this expression has been defined. Is null when the expression is not canonical.
interface BoxedExpressionshape: number[] Permalink
The shape describes the axis of the expression.
When the expression is a scalar (number), the shape is []
.
When the expression is a vector, the shape is [n]
.
When the expression is a matrix, the shape is [n, m]
.
interface BoxedExpressionsimplify() Permalink
Return a simpler form of the canonical form of this expression.
A series of rewriting rules are applied repeatedly, until no more rules apply.
If a custom simplify
handler is associated with this function
definition, it is invoked.
The values assigned to symbols and the assumptions about symbols may be
used, for example arg.isInteger
or arg.isPositive
.
No calculations involving decimal numbers (numbers that are not integers) are performed but exact calculations may be performed, for example:
\( \sin(\frac{\pi}{4}) \longrightarrow \frac{\sqrt{2}}{2} \).
The result is in canonical form.
interface BoxedExpressionsolve() Permalink
interface BoxedExpressionsubexpressions: BoxedExpression[] Permalink
All the subexpressions in this expression, recursively
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionsubs() Permalink
Replace all the symbols in the expression as indicated.
Note the same effect can be achieved with this.replace()
, but
using this.subs()
is more efficient, and simpler.
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionsymbolDefinition: undefined | BoxedSymbolDefinition Permalink
For symbols, a possible definition associated with the expression.
Note undefined
if not a symbol
interface BoxedExpressionsymbols: string[] Permalink
All the symbols in the expression, recursively
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionunknowns: string[] Permalink
All the identifiers used in the expression that do not have a value associated with them, i.e. they are declared but not defined.
interface BoxedExpressionurl: undefined | string Permalink
An optional URL pointing to more information about the symbol or function head.
Note undefined
if not a canonical expression.
interface BoxedExpressionwikidata: undefined | string Permalink
Wikidata identifier.
Note undefined
if not a canonical expression.
interface BoxedExpressioncanonical: BoxedExpression read only Permalink
Return the canonical form of this expression.
If this is a function expressin, a definition is associated with the canonical expression.
When determining the canonical form the following function definition flags are applied:
associative
: \( f(a, f(b), c) \longrightarrow f(a, b, c) \)idempotent
: \( f(f(a)) \longrightarrow f(a) \)involution
: \( f(f(a)) \longrightarrow a \)commutative
: sort the arguments.
If his expression is already canonical, the value of canonical is
this
.
interface BoxedExpressiondomain Permalink
The domain of the value of this expression.
If a function expression, the domain of the value of the function (the codomain of the function).
If a symbol the domain of the value of the symbol.
Use expr.head
to determine if an expression is a symbol or function
expression.
Note: if non-canonical or not valid, return undefined
.
Modify the domain of a symbol.
Note: If non-canonical, does nothing.
interface BoxedExpressionisCanonical: boolean Permalink
If true
, this expression is in a canonical form.
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionlatex: string Permalink
LaTeX representation of this expression.
The serialization can be customized with ComputeEngine.latexOptions
Note applicable to canonical and non-canonical expressions.
interface BoxedExpressionvalue Permalink
Return a JavaScript primitive representing the value of this expression.
Equivalent to expr.N().valueOf()
.
Only the value of variables can be changed (symbols that are not constants).
Throws a runtime error if a constant.
Note: If non-canonical, does nothing.
Primitive Methods
interface BoxedExpression[toPrimitive]() Permalink
Similar toexpr.valueOf()
but includes a hint.
interface BoxedExpressionis() Permalink
From Object.is()
. Equivalent to BoxedExpression.isSame()
interface BoxedExpressionprint() Permalink
Output to the console a string representation of the expression.
interface BoxedExpressiontoJSON() Permalink
Used by JSON.stringify()
to serialize this object to JSON.
Method version of expr.json
.
interface BoxedExpressiontoString() Permalink
From Object.toString()
, return a string representation of the
expression. This string is suitable to be output to the console
for debugging, for example. To get a LaTeX representation of the
expression, use expr.latex
.
Used when coercing a BoxedExpression
to a String
.
interface BoxedExpressionvalueOf() Permalink
From Object.valueOf()
, return a primitive value for the expression.
If the expression is a machine number, or bignum or rational that can be
converted to a machine number, return a JavaScript number
.
If the expression is a symbol, return the name of the symbol as a string
.
Otherwise return a JavaScript primitive representation of the expression.
Relational Operator
interface BoxedExpressionisEqual() Permalink
Mathematical equality (strong equality), that is the value
of this expression and of rhs
are numerically equal.
The numeric value of both expressions are compared.
Numbers whose difference is less than engine.tolerance
are
considered equal. This tolerance is set when the engine.precision
is
changed to be such that the last two digits are ignored.
interface BoxedExpressionisGreater() Permalink
The numeric value of both expressions are compared.
interface BoxedExpressionisGreaterEqual() Permalink
The numeric value of both expressions are compared.
interface BoxedExpressionisLess() Permalink
If the expressions cannot be compared, return undefined
The numeric value of both expressions are compared.
interface BoxedExpressionisLessEqual() Permalink
The numeric value of both expressions are compared.
interface BoxedExpressionisSame() Permalink
Structural/symbolic equality (weak equality).
ce.parse('1+x').isSame(ce.parse('x+1'))
is false
Note applicable to canonical and non-canonical expressions.
interface BoxedSymbolDefinition Permalink
Extends BoxedBaseDefinition, SymbolAttributes, Partial<NumericFlags>
interface BoxedSymbolDefinitionProperties / Methods
interface BoxedSymbolDefinitiondomain: undefined | BoxedDomain Permalink
interface BoxedSymbolDefinitioninferredDomain: boolean Permalink
interface BoxedSymbolDefinitionvalue Permalink
class ComputeEngine Permalink
Implements IComputeEngine
To use the CortexJS Compute Engine, create a ComputeEngine
instance, or if using a
mathfield, use the default Compute Engine instance from the MathfieldElement
class: ce = MathfieldElement.computeEngine
.
Use the instance to create boxed expressions with ce.parse()
and ce.box()
.
const ce = new ComputeEngine();
let expr = ce.parse("e^{i\\pi}");
console.log(expr.N().latex);
// ➔ "-1"
expr = ce.box(["Expand", ["Power", ["Add", "a", "b"], 2]]);
console.log(expr.evaluate().latex);
// ➔ "a^2 + 2ab + b^2"
class ComputeEnginenew ComputeEngine() Permalink
-
options?:
- ids: readonly Readonly<{[id: string]: IdentifierDefinition}>[];
- numericMode: NumericMode;
The default mode is
"auto"
. Use"machine"
to perform numeric calculations using 64-bit floats. Use"bignum"
to perform calculations using arbitrary precision floating point numbers. Use"auto"
or"complex"
to allow calculations on complex numbers.- numericPrecision: number;
Specific how many digits of precision for the numeric calculations. Default is 100.
- tolerance: number;
If the absolute value of the difference of two numbers is less than
tolerance
, they are considered equal. Used bychop()
as well.
- → ComputeEngine
Construct a new ComputeEngine
instance.
Identifier tables define functions and symbols (in options.ids
).
If no table is provided the MathJSON Standard Library is used (ComputeEngine.getStandardLibrary()
)
The LaTeX syntax dictionary is defined in options.latexDictionary
.
The order of the dictionaries matter: the definitions from the later ones
override the definitions from earlier ones. The first dictionary should
be the 'core'
dictionary which include some basic definitions such
as domains (Booleans
, Numbers
, etc…) that are used by later
dictionaries.
class ComputeEngineProperties / Methods
- Anything
- Booleans
- ComplexInfinity
- E
- False
- Half
- I
- NaN
- NegativeInfinity
- NegativeOne
- Nothing
- Numbers
- One
- Pi
- PositiveInfinity
- Strings
- True
- Void
- Zero
- _defineFunction
- _defineSymbol
- add
- array
- ask
- assign
- assume
- assumptions
- bignum
- box
- canonical
- chop
- complex
- context
- costFunction
- declare
- div
- domain
- domainError
- error
- forget
- function
- getLatexDictionary
- getStandardLibrary
- hold
- inv
- isBignum
- isComplex
- iterationLimit
- jsonSerializationOptions
- latexDictionary
- latexOptions
- lookupFunction
- lookupSymbol
- mul
- neg
- number
- numericMode
- pair
- parse
- pattern
- popScope
- pow
- precision
- pushScope
- rawJson
- recursionLimit
- rules
- serialize
- sqrt
- stats
- strict
- string
- swapScope
- symbol
- timeLimit
- tolerance
- tuple
- verify
class ComputeEngineAnything: BoxedDomain Permalink
class ComputeEngineBooleans: BoxedDomain Permalink
class ComputeEngineComplexInfinity: BoxedExpression Permalink
class ComputeEngineE: BoxedExpression Permalink
class ComputeEngineFalse: BoxedExpression Permalink
class ComputeEngineHalf: BoxedExpression Permalink
class ComputeEngineI: BoxedExpression Permalink
class ComputeEngineNaN: BoxedExpression Permalink
class ComputeEngineNegativeInfinity: BoxedExpression Permalink
class ComputeEngineNegativeOne: BoxedExpression Permalink
class ComputeEngineNothing: BoxedExpression Permalink
class ComputeEngineNumbers: BoxedDomain Permalink
class ComputeEngineOne: BoxedExpression Permalink
class ComputeEnginePi: BoxedExpression Permalink
class ComputeEnginePositiveInfinity: BoxedExpression Permalink
class ComputeEngineStrings: BoxedDomain Permalink
class ComputeEngineTrue: BoxedExpression Permalink
class ComputeEngineVoid: BoxedDomain Permalink
class ComputeEngineZero: BoxedExpression Permalink
class ComputeEngine_defineFunction() Permalink
class ComputeEngine_defineSymbol() Permalink
class ComputeEngineadd() Permalink
Shortcut for this.box(["Add", ...]).evaluate()
.
class ComputeEnginearray() Permalink
class ComputeEngineask() Permalink
Return a list of all the assumptions that match a pattern.
ce.assume(['Element', 'x', 'PositiveIntegers');
ce.ask(['Greater', 'x', '_val'])
// -> [{'val': 0}]
class ComputeEngineassign() Permalink
Assign a value to an identifier in the current scope.
Use undefined
to reset the identifier to no value.
The identifier should be a valid MathJSON identifier not a LaTeX string.
The identifier can take the form “f(x, y”) to create a function with two parameters, “x” and “y”.
If the id was not previously declared, an automatic declaration
is done. The domain of the identifier is inferred from the value.
To more precisely define the domain of the identifier, use ce.declare()
instead, which allows you to specify the domain, value and other
attributes of the identifier.
class ComputeEngineassume() Permalink
Add an assumption.
Note that the assumption is put into canonical form before being added.
class ComputeEngineassumptions: ExpressionMapInterface<boolean> read only Permalink
class ComputeEnginebignum() Permalink
Create an arbitrary precision number.
The return value is an object with methods to perform arithmetic operations:
-
toNumber()
: convert to a JavaScriptnumber
with potential loss of precision -
add()
-
sub()
-
neg()
(unary minus) -
mul()
-
div()
-
pow()
-
sqrt()
(square root) -
cbrt()
(cube root) -
exp()
(e^x) -
log()
-
ln()
(natural logarithm) -
mod()
-
abs()
-
ceil()
-
floor()
-
round()
-
equals()
-
gt()
-
gte()
-
lt()
-
lte()
-
cos()
-
sin()
-
tanh()
-
acos()
-
asin()
-
atan()
-
cosh()
-
sinh()
-
acosh()
-
asinh()
-
atanh()
-
isFinite()
-
isInteger()
-
isNaN()
-
isNegative()
-
isPositive()
-
isZero()
-
sign()
(1, 0 or -1)
class ComputeEnginebox() Permalink
-
expr:
- | SemiBoxedExpression
- | [num: number, denom: number]
-
options?:
- canonical: boolean | CanonicalForm | CanonicalForm[];
- → BoxedExpression
Return a boxed expression from the input.
class ComputeEnginecanonical() Permalink
Return a canonical version of an array of semi-boxed-expressions.
class ComputeEnginechop() Permalink
Replace a number that is close to 0 with the exact integer 0.
How close to 0 the number has to be to be considered 0 is determined by tolerance.
class ComputeEnginecomplex() Permalink
Create a complex number. The return value is an object with methods to perform arithmetic operations:
re
(real part, as a JavaScriptnumber
)im
(imaginary part, as a JavaScriptnumber
)add()
sub()
neg()
(unary minus)mul()
div()
pow()
sqrt()
(square root)exp()
(e^x)log()
ln()
(natural logarithm)mod()
-
abs()
-
ceil()
-
floor()
-
round()
-
arg()
the angle of the complex number -
inverse()
the inverse of the complex number 1/z -
conjugate()
the conjugate of the complex number -
equals()
-
cos()
-
sin()
-
tanh()
-
acos()
-
asin()
-
atan()
-
cosh()
-
sinh()
-
acosh()
-
asinh()
-
atanh()
-
isFinite()
-
isNaN()
-
isZero()
-
sign()
(1, 0 or -1)
class ComputeEnginecontext: null | RuntimeScope Permalink
The current scope.
A scope stores the definition of symbols and assumptions.
Scopes form a stack, and definitions in more recent scopes can obscure definitions from older scopes.
The ce.context
property represents the current scope.
class ComputeEnginecostFunction Permalink
class ComputeEnginedeclare() Permalink
Declare an identifier: specify their domain, and other attributes, including optionally a value.
Once the domain of an identifier has been declared, it cannot be changed. The domain information is used to calculate the canonical form of expressions and ensure they are valid. If the domain could be changed after the fact, previously valid expressions could become invalid.
Use the Anyting
domain for a very generic domain.
class ComputeEnginediv() Permalink
Shortcut for this.box(["Divide", num, denom]).evaluate()
The result is canonical.
class ComputeEnginedomain() Permalink
Return a canonical boxed domain.
If the domain is invalid, may return an ["Error"]
expression
class ComputeEnginedomainError() Permalink
- expectedDomain:
-
actualDomain:
- | undefined
- | BoxedDomain
- where?: SemiBoxedExpression
- → BoxedExpression
class ComputeEngineerror() Permalink
-
message:
- | string
- | [string, ...SemiBoxedExpression[]]
- where?: SemiBoxedExpression
- → BoxedExpression
Shortcut for this.box(["Error",...])
.
The result is canonical.
class ComputeEngineforget() Permalink
Remove all assumptions about one or more symbols
class ComputeEnginefunction() Permalink
- head: string
- ops: SemiBoxedExpression[]
-
options?:
- canonical: boolean;
- metadata: Metadata;
- → BoxedExpression
class ComputeEnginegetLatexDictionary() Permalink
class ComputeEnginegetStandardLibrary() Permalink
Return identifier tables suitable for the specified categories, or "all"
for all categories ("arithmetic"
, "algebra"
, etc…).
An identifier table defines how the symbols and function names in a MathJSON expression should be interpreted, i.e. how to evaluate and manipulate them.
class ComputeEnginehold() Permalink
Add a["Hold"]
wrapper to `expr.
class ComputeEngineinv() Permalink
Shortcut for this.box(["Divide", 1, expr]).evaluate()
class ComputeEngineisBignum() Permalink
class ComputeEngineisComplex() Permalink
class ComputeEngineiterationLimit: number read only Permalink
class ComputeEnginejsonSerializationOptions Permalink
Options to control the serialization to MathJSON when using BoxedExpression.json
.
class ComputeEnginelatexDictionary: readonly LatexDictionaryEntry[] Permalink
class ComputeEnginelatexOptions Permalink
Options to control the serialization of MathJSON expression to LaTeX
when using this.latex
or this.engine.serialize()
.
class ComputeEnginelookupFunction() Permalink
Return the definition for a function matching this head.
Start looking in the current context, than up the scope chain.
This is a very rough lookup, since it doesn’t account for the domain
of the argument or the codomain. However, it is useful during parsing
to differentiate between symbols that might represent a function application, e.g. f
vs x
.
class ComputeEnginelookupSymbol() Permalink
Return a matching symbol definition, starting with the current scope and going up the scope chain. Prioritize finding a match by wikidata, if provided.
class ComputeEnginemul() Permalink
Shortcut for this.box(["Multiply", ...]).evaluate()
class ComputeEngineneg() Permalink
Shortcut for this.box(["Negate", expr]).evaluate()
class ComputeEnginenumber() Permalink
-
value:
- | string
- | number
- | bigint
- | Decimal
- | Complex
- | MathJsonNumber
- | Rational
-
options?:
- canonical: boolean;
- metadata: Metadata;
- → BoxedExpression
This function tries to avoid creating a boxed number if num
corresponds
to a common value for which we have a shared instance (-1, 0, NaN, etc…)
class ComputeEnginenumericMode: NumericMode Permalink
The numeric evaluation mode:
Mode | |
---|---|
"auto" |
Use bignum or complex numbers. |
"machine" |
IEEE 754-2008, 64-bit floating point numbers: 52-bit mantissa, about 15 digits of precision |
"bignum" |
Arbitrary precision floating point numbers, as provided by the “decimal.js” library |
"complex" |
Complex number represented by two machine numbers, a real and an imaginary part, as provided by the “complex.js” library |
class ComputeEnginepair() Permalink
Shortcut for this.box(["Pair", ...])
The result is canonical.
class ComputeEngineparse() Permalink
- latex: string
-
options?:
- canonical: boolean | CanonicalForm | CanonicalForm[];
- → BoxedExpression
Parse a string of LaTeX and return a corresponding BoxedExpression
.
The result may not be canonical.
- s: null
-
options?:
- canonical: boolean | CanonicalForm | CanonicalForm[];
- → null
-
latex:
- | null
- | string
-
options?:
- canonical: boolean | CanonicalForm | CanonicalForm[];
- → null | BoxedExpression
class ComputeEnginepattern() Permalink
class ComputeEnginepopScope() Permalink
Remove the most recent scope from the scope stack, and set its parent scope as current.
class ComputeEnginepow() Permalink
Shortcut for this.box(["Power", base, exponent]).evaluate()
class ComputeEngineprecision Permalink
The precision, or number of significant digits, of numeric
calculations when the numeric mode is "auto"
or "bignum"
.
To make calculations using more digits, at the cost of expanded memory
usage and slower computations, set the precision
higher.
If the numeric mode is not "auto"
or "bignum"
, it is set to "auto"
.
Trigonometric operations are accurate for precision up to 1,000.
class ComputeEnginepushScope() Permalink
Create a new scope and add it to the top of the scope stack
The scope
argument can be used to specify custom precision,
etc… for this scope
class ComputeEnginerawJson() Permalink
class ComputeEnginerecursionLimit: number read only Permalink
class ComputeEnginerules() Permalink
class ComputeEngineserialize() Permalink
Serialize a BoxedExpression
or a MathJSON
expression to
a LaTeX string
class ComputeEnginesqrt() Permalink
Shortcut for this.box(["Sqrt", base]).evaluate()
class ComputeEnginestats: ComputeEngineStats read only Permalink
class ComputeEnginestrict: boolean Permalink
In strict mode (the default) the Compute Engine performs validation of domains and signature and may report errors.
When strict mode is off, results may be incorrect or generate JavaScript errors if the input is not valid.
class ComputeEnginestring() Permalink
class ComputeEngineswapScope() Permalink
Set the current scope, return the previous scope.
class ComputeEnginesymbol() Permalink
Return a boxed symbol
class ComputeEnginetimeLimit: number read only Permalink
class ComputeEnginetolerance: number Permalink
Values smaller than the tolerance are considered to be zero for the
purpose of comparison, i.e. if |b - a| <= tolerance
, b
is considered
equal to a
.
class ComputeEnginetuple() Permalink
Shortcut for this.box(["Tuple", ...])
The result is canonical.
class ComputeEngineverify() Permalink
Answer a query based on the current assumptions.
interface ComputeEngineStats Permalink
- expressions: null | Set<BoxedExpression> Permalink
- highwaterMark: number Permalink
- symbols: Set<BoxedExpression> Permalink
interface ExpressionMapInterface Permalink
- [iterator] Permalink (): IterableIterator<[BoxedExpression, U]>
- clear Permalink (): void
- delete Permalink (expr: BoxedExpression): void
- entries Permalink (): IterableIterator<[BoxedExpression, U]>
- get Permalink (expr: BoxedExpression): undefined | U
- has Permalink (expr: BoxedExpression): boolean
- set Permalink (expr: BoxedExpression, value: U): void
class LatexSyntax Permalink
To customize the parsing and serializing of LaTeX syntax, create a LatexSyntax
instance.
class LatexSyntaxnew LatexSyntax() Permalink
class LatexSyntaxMethods / Properties
class LatexSyntaxgetDictionary() Permalink
Return a LaTeX dictionary suitable for the specified category, or "all"
for all categories ("arithmetic"
, "algebra"
, etc…).
A LaTeX dictionary is needed to translate between LaTeX and MathJSON.
Each entry in the dictionary indicate how a LaTeX token (or string of tokens) should be parsed into a MathJSON expression.
For example an entry can define that the \pi
LaTeX token should map to the
symbol "Pi"
, or that the token -
should map to the function
["Negate",...]
when in a prefix position and to the function
["Subtract", ...]
when in an infix position.
Furthermore, the information in each dictionary entry is used to serialize the LaTeX string corresponding to a MathJSON expression.
Use the value returned by this function to the options
argument of the
constructor.
class LatexSyntaxparse() Permalink
class LatexSyntaxserialize() Permalink
interface Parser Permalink
interface ParserProperties / Methods
- addBoundary
- atBoundary
- atEnd
- atTerminator
- boundaryError
- computeEngine
- error
- index
- latex
- match
- matchAll
- matchAny
- matchBoundary
- matchChar
- nextToken
- options
- parseArguments
- parseExpression
- parseGroup
- parseOptionalGroup
- parsePostfixOperator
- parseStringGroup
- parseSymbol
- parseTabular
- parseToken
- peek
- removeBoundary
- skipSpace
- skipVisualSpace
interface ParseraddBoundary() Permalink
Boundaries are used to detect the end of an expression.
They are used for unusual syntactic constructs, for example
\int \sin x dx
where the dx
is not an argument to the \sin
function, but a boundary of the integral.
They are also useful when handling syntax errors and recovery.
For example, \begin{bmatrix} 1 & 2 { \end{bmatrix}
has an
extraneous {
, but the parser will attempt to recover and continue
parsing when it encounters the \end{bmatrix}
boundary.
interface ParseratBoundary: boolean read only Permalink
interface ParseratEnd: boolean Permalink
True if the last token has been reached.
Consider also atTerminator()
.
interface ParseratTerminator() Permalink
Return true if the terminator condition is met or if the last token has been reached.
interface ParserboundaryError() Permalink
interface ParsercomputeEngine: IComputeEngine Permalink
interface Parsererror() Permalink
-
code:
- | string
- | [string, ...Expression[]]
- fromToken: number
- → Expression
Return an error expression with the specified code and arguments
interface Parserindex: number Permalink
The index of the current token
interface Parserlatex() Permalink
Return a string representation of the expression
between start
and end
(default: the whole expression)
interface Parsermatch() Permalink
If the next token matches the target advance and return true. Otherwise return false
interface ParsermatchAll() Permalink
Return true if the next tokens match the argument, an array of tokens, or null otherwise
interface ParsermatchAny() Permalink
Return the next token if it matches any of the token in the argument or null otherwise
interface ParsermatchBoundary() Permalink
interface ParsermatchChar() Permalink
If the next token is a character, return it and advance the index
This includes plain characters (e.g. ‘a’, ‘+’…), characters
defined in hex (^^ and ^^^^), the \char
and \unicode
command.
interface ParsernextToken() Permalink
Return the next token and advance the index
interface Parseroptions: Required<ParseLatexOptions> Permalink
interface ParserparseArguments() Permalink
Parse an argument list, for example: (12, x+1)
or \left(x\right)
- ‘enclosure’ : will look for arguments inside an enclosure (an open/close fence) (default)
- ‘implicit’: either an expression inside a pair of
()
, or just a primary (i.e. we interpret\cos x + 1
as\cos(x) + 1
)
Return an array of expressions, one for each argument, or null
if no
argument was found.
interface ParserparseExpression() Permalink
Parse an expression:
<expression> ::=
| <primary> ( <infix-op> <expression> )?
| <prefix-op> <expression>
<primary> :=
(<number> | <symbol> | <function-call> | <matchfix-expr>)
(<subsup> | <postfix-operator>)*
<matchfix-expr> :=
<matchfix-op-open> <expression> <matchfix-op-close>
<function-call> ::=
| <function><matchfix-op-group-open><expression>[',' <expression>]<matchfix-op-group-close>
This is the top-level parsing entry point.
Stop when an operator of precedence less than until.minPrec
or the sequence of tokens until.tokens
is encountered
until
is { minPrec:0 }
by default.
interface ParserparseGroup() Permalink
Parse an expression in aLaTeX group enclosed in curly brackets {}
.
These are often used as arguments to LaTeX commands, for example
\frac{1}{2}
.
Return null
if none was found
Return ['Sequence']
if an empty group {}
was found
interface ParserparseOptionalGroup() Permalink
Parse an expression enclosed in a LaTeX optional group enclosed in square brackets []
.
Return null
if none was found.
interface ParserparsePostfixOperator() Permalink
Parse a postfix operator, such as '
or !
.
Prefix, infix and matchfix operators are handled by parseExpression()
interface ParserparseStringGroup() Permalink
Some LaTeX commands have arguments that are not interpreted as
expressions, but as strings. For example, \begin{array}{ccc}
(both
array
and ccc
are strings), \color{red}
or \operatorname{lim sup}
.
If the next token is the start of a group ({
), return the content
of the group as a string. This may include white space, and it may need
to be trimmed at the start and end of the string.
LaTeX commands are typically not allowed inside a string group (for example,
\alpha
would result in an error), but we do not enforce this.
If optional
is true, this should be an optional group in square brackets
otherwise it is a regular group in braces.
interface ParserparseSymbol() Permalink
A symbol can be:
- a single-letter identifier:
x
- a single LaTeX command:
\pi
- a multi-letter identifier:
\operatorname{speed}
interface ParserparseTabular() Permalink
Parse an expression in a tabular format, where rows are separated by \\
and columns by &
.
Return rows of sparse columns: empty rows are indicated with Nothing
,
and empty cells are also indicated with Nothing
.
interface ParserparseToken() Permalink
Some LaTeX commands (but not all) can accept arguments as single
tokens (i.e. without braces), for example ^2
, \sqrt3
or \frac12
This argument will usually be a single token, but can be a sequence of
tokens (e.g. \sqrt\frac12
or \sqrt\operatorname{speed}
).
The following tokens are excluded from consideration in order to fail
early when encountering a likely syntax error, for example x^(2)
instead of x^{2}
. With (
in the list of excluded tokens, the
match will fail and the error can be recovered.
The excluded tokens include !"#$%&(),/;:?@[]
|~", \left
, \bigl
, etc…
interface Parserpeek: string Permalink
Return the next token, without advancing the index
interface ParserremoveBoundary() Permalink
interface ParserskipSpace() Permalink
If there are any space, advance the index until a non-space is encountered
interface ParserskipVisualSpace() Permalink
Skip over “visual space” which
includes space tokens, empty groups {}
, and commands such as \,
and \!
interface Pattern Permalink
Extends BoxedExpression
interface PatternProperties / Methods
Dictionary Expression
Domain Properties
Expression Properties
Function Expression
Numeric Expression
String Expression
Symbol Expression
Other
Primitive Methods
Relational Operator
Dictionary Expression
Domain Properties
Expression Properties
Function Expression
Numeric Expression
String Expression
Symbol Expression
Other
interface Patterncount() Permalink
Return the number of exprs that matched the pattern
interface Patterntest() Permalink
If expr
matches the pattern, return true
, otherwise false
Primitive Methods
Relational Operator
interface Serializer Permalink
interface SerializerProperties / Methods
interface SerializerapplyFunctionStyle() Permalink
Styles
interface Serializercanonical: boolean Permalink
If true, apply transformations to the expression so the output doesn’t necesarily match the raw MathJSON, but is more visually pleasing and easier to read. If false, output the raw MathJSON.
interface SerializerfractionStyle() Permalink
interface SerializergroupStyle() Permalink
interface Serializerlevel: number Permalink
“depth” of the expression:
- 0 for the root
- 1 for the arguments of the root
- 2 for the arguments of the arguments of the root
- etc…
This allows for variation of the LaTeX serialized based
on the depth of the expression, for example using \Bigl(
for the top level, and \bigl(
or (
for others.
interface SerializerlogicStyle() Permalink
interface SerializernumericSetStyle() Permalink
interface SerializeronError: WarningSignalHandler Permalink
interface Serializeroptions: Required<SerializeLatexOptions> Permalink
interface SerializerpowerStyle() Permalink
interface SerializerrootStyle() Permalink
interface Serializerserialize() Permalink
Output a LaTeX string representing the expression
interface SerializerserializeFunction() Permalink
interface SerializerserializeSymbol() Permalink
interface Serializerwrap() Permalink
Add a group fence around the expression if it is
an operator of precedence less than or equal to prec
.
interface SerializerwrapArguments() Permalink
A string with the arguments of expr fenced appropriately and separated by commas.
interface SerializerwrapShort() Permalink
Add a group fence around the expression if it is short (not a function)
interface SerializerwrapString() Permalink
Output s
surrounded by delimiters.
If delimiters
is not specified, use ()
ADDITION_PRECEDENCE Permalink
ARROW_PRECEDENCE Permalink
ASSIGNMENT_PRECEDENCE Permalink
COMPARISON_PRECEDENCE Permalink
DIVISION_PRECEDENCE Permalink
EXPONENTIATION_PRECEDENCE Permalink
MULTIPLICATION_PRECEDENCE Permalink
POSTFIX_PRECEDENCE Permalink
version Permalink
module compute-engineTypes
- ArrayValue
- AssignValue
- AssumeResult
- BaseDefinition
- BaseEntry
- BoxedFunctionDefinition
- BoxedFunctionSignature
- BoxedRule
- BoxedRuleSet
- BoxedSubstitution
- CanonicalForm
- CollectionHandlers
- CompiledExpression
- DefaultEntry
- Delimiter
- DelimiterScale
- DomainCompatibility
- DomainConstructor
- DomainExpression
- DomainLiteral
- EnvironmentEntry
- EnvironmentParseHandler
- EvaluateOptions
- ExpressionEntry
- ExpressionParseHandler
- FunctionDefinition
- FunctionDefinitionFlags
- FunctionEntry
- FunctionParseHandler
- FunctionSignature
- Hold
- IdentifierDefinition
- IdentifierDefinitions
- InfixEntry
- InfixParseHandler
- JsonSerializationOptions
- LatexArgumentType
- LatexDictionary
- LatexDictionaryEntry
- LatexString
- LatexToken
- LibraryCategory
- MatchfixEntry
- MatchfixParseHandler
- Metadata
- NumberFormattingOptions
- NumericFlags
- NumericMode
- ParseLatexOptions
- PatternConditionFunction
- PatternMatchOptions
- PatternReplaceFunction
- PostfixEntry
- PostfixParseHandler
- Precedence
- PrefixEntry
- PrefixParseHandler
- Rational
- ReplaceOptions
- Rule
- RuntimeIdentifierDefinitions
- RuntimeScope
- Scope
- SemiBoxedExpression
- SerializeHandler
- SerializeLatexOptions
- SimplifyOptions
- Substitution
- SymbolAttributes
- SymbolDefinition
- SymbolEntry
- SymbolParseHandler
- Terminator
- Trigger
ArrayValue Permalink
- | boolean
- | number
- | string
- | Decimal
- | Complex
- | BoxedExpression
- | undefined
AssignValue Permalink
- | boolean
- | number
- | string
- | Decimal
- | Complex
- | LatexString
- | SemiBoxedExpression
- | (ce: any, args: any): BoxedExpression
- | undefined
AssumeResult Permalink
- | "internal-error"
- | "not-a-predicate"
- | "contradiction"
- | "tautology"
- | "ok"
BaseDefinition Permalink
- description: string | string[];
A short (about 1 line) description. May contain Markdown.
- url: string;
A URL pointing to more information about this symbol or head.
- wikidata: string;
A short string representing an entry in a wikibase.
For example
Q167
is the wikidata entry for thePi
constant.
BaseEntry Permalink
Maps a string of LaTeX tokens to a function or symbol and vice-versa.
- name: string;
Map a MathJSON function or symbol name to this entry.
Each entry should have at least a
name
or aparse
handler.An entry with no
name
cannot be serialized: thename
is used to map a MathJSON function or symbol name to the appropriate entry for serializing. However, an entry with noname
can be used to define a synonym (for example for the symbol\varnothing
which is a synonym for\emptyset
).If no
parse
handler is provided, only the trigger is used to select this entry. Otherwise, if the trigger of the entry matches the current token, theparse
handler is invoked.- serialize: LatexString | SerializeHandler;
Transform an expression into a LaTeX string. If no
serialize
handler is provided, thetrigger
property is used
BoxedFunctionDefinition Permalink
- BoxedBaseDefinition &
- Partial<CollectionHandlers> &
- FunctionDefinitionFlags &
- complexity: number;
- hold: Hold;
- signature: BoxedFunctionSignature;
BoxedFunctionSignature Permalink
- inferredSignature: boolean;
- optParams: BoxedDomain[];
- params: BoxedDomain[];
- restParam: BoxedDomain;
- result: BoxedDomain | (ce: IComputeEngine, args: BoxedExpression[]): BoxedDomain | null | undefined;
- N?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | BoxedExpression;
- canonical?: (ce: IComputeEngine, args: BoxedExpression[]): null | BoxedExpression;
- compile?: (expr: BoxedExpression): CompiledExpression;
- evalDimension?: (ce: IComputeEngine, args: BoxedExpression[]): BoxedExpression;
- evaluate?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | BoxedExpression;
- sgn?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | 0 | 1 | -1;
- simplify?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | BoxedExpression;
BoxedRule Permalink
- condition: undefined | PatternConditionFunction;
- id: string;
- match: Pattern;
- priority: number;
- replace: BoxedExpression | PatternReplaceFunction;
BoxedRuleSet Permalink
BoxedSubstitution Permalink
CanonicalForm Permalink
- | "InvisibleOperator"
- | "Number"
- | "Multiply"
- | "Add"
- | "Power"
- | "Divide"
- | "Flatten"
- | "Order"
CollectionHandlers Permalink
The handlers are the primitive operations that can be performed on collections.
There are two types of collections:
- finite collections, such as lists, tuples, sets, matrices, etc…
The
size()
handler of finite collections returns the number of elements - infinite collections, such as sequences, ranges, etc…
The
size()
handler of infinite collections returnsInfinity
Infinite collections are not indexable, they have noat()
handler.
- at: (expr: BoxedExpression, index: string | number): undefined | BoxedExpression;
Return the element at the specified index. The first element is
at(1)
, the last element isat(-1)
. If the index is <0, return the element at indexsize() + index + 1
. The index can also be a string for example for dictionaries. If the index is invalid, returnundefined
.- indexOf: (expr: BoxedExpression, target: BoxedExpression, from?: number): undefined | string | number;
Return the index of the first element that matches the target expression. The comparison is done using the
target.isEqual()
method. If the expression is not found, returnundefined
. If the expression is found, return the index, 1-based. If the expression is found multiple times, return the index of the first match.From is the starting index for the search. If negative, start from the end and search backwards.
- iterator: (expr: BoxedExpression, start?: number, count?: number): Iterator<BoxedExpression, undefined, undefined>;
Return an iterator
- start is optional and is a 1-based index.
- if start is not specified, start from index 1
- count is optional and is the number of elements to return
- if count is not specified or negative, return all the elements from start to the end
If there is a
keys()
handler, there is noiterator()
handler.- keys: (expr: BoxedExpression): undefined | Iterator<string, any, undefined>;
If the collection is indexed by strings, return the valid values for the index.
- size: (expr: BoxedExpression): number;
Return the number of elements in the collection. An empty collection has a size of 0.
CompiledExpression Permalink
- evaluate?: (scope: {[symbol: string]: BoxedExpression}): number | BoxedExpression;
DefaultEntry Permalink
- BaseEntry &
- Trigger &
- parse: Expression | ExpressionParseHandler;
Delimiter Permalink
Open and close delimiters that can be used with MatchfixEntry record to define new LaTeX dictionary entries.
- | ")"
- | "("
- | "]"
- | "["
- | "{"
- | "}"
- | "<"
- | ">"
- | "|"
- | "||"
- | "\lceil"
- | "\rceil"
- | "\lfloor"
- | "\rfloor"
DelimiterScale Permalink
- | "normal"
- | "scaled"
- | "big"
- | "none"
DomainCompatibility Permalink
- | "covariant"
- | "contravariant"
- | "bivariant"
- | "invariant"
DomainConstructor Permalink
A domain constructor is the head of a domain expression.
- | "FunctionOf"
- | "ListOf"
- | "DictionaryOf"
- | "TupleOf"
- | "Intersection"
- | "Union"
- | "OptArg"
- | "VarArg"
- | "Covariant"
- | "Contravariant"
- | "Bivariant"
- | "Invariant"
DomainExpression Permalink
- | DomainLiteral
- | ["Union", ...DomainExpression<T>[]]
- | ["Intersection", ...DomainExpression<T>[]]
- | ["ListOf", DomainExpression<T>]
- | ["DictionaryOf", DomainExpression<T>]
- | ["TupleOf", ...DomainExpression<T>[]]
- | ["OptArg", ...DomainExpression<T>[]]
- | ["VarArg", DomainExpression<T>]
- | ["Covariant", DomainExpression<T>]
- | ["Contravariant", DomainExpression<T>]
- | ["Bivariant", DomainExpression<T>]
- | ["Invariant", DomainExpression<T>]
- | ["FunctionOf", ...DomainExpression<T>[]]
DomainLiteral Permalink
- | "Anything"
- | "Values"
- | "Domains"
- | "Void"
- | "NothingDomain"
- | "Booleans"
- | "Strings"
- | "Symbols"
- | "Collections"
- | "Lists"
- | "Dictionaries"
- | "Sequences"
- | "Tuples"
- | "Sets"
- | "Functions"
- | "Predicates"
- | "LogicOperators"
- | "RelationalOperators"
- | "NumericFunctions"
- | "RealFunctions"
- | "Numbers"
- | "ComplexNumbers"
- | "ExtendedRealNumbers"
- | "ImaginaryNumbers"
- | "Integers"
- | "Rationals"
- | "PositiveNumbers"
- | "PositiveIntegers"
- | "NegativeNumbers"
- | "NegativeIntegers"
- | "NonNegativeNumbers"
- | "NonNegativeIntegers"
- | "NonPositiveNumbers"
- | "NonPositiveIntegers"
- | "ExtendedComplexNumbers"
- | "TranscendentalNumbers"
- | "AlgebraicNumbers"
- | "RationalNumbers"
- | "RealNumbers"
EnvironmentEntry Permalink
A LaTeX dictionary entry for an environment, that is a LaTeX
construct using \begin{...}...\end{...}
.
- BaseEntry &
- identifierTrigger: string;
- kind: "environment";
- parse: EnvironmentParseHandler;
EnvironmentParseHandler Permalink
EvaluateOptions Permalink
Options for BoxedExpression.evaluate()
- numericMode: boolean;
ExpressionEntry Permalink
- BaseEntry &
- Trigger &
- kind: "expression";
- parse: Expression | ExpressionParseHandler;
- precedence: Precedence;
ExpressionParseHandler Permalink
FunctionDefinition Permalink
Definition record for a function.
- BaseDefinition &
- Partial<CollectionHandlers> &
- Partial<FunctionDefinitionFlags> &
- complexity: number;
A number used to order arguments.
Argument with higher complexity are placed after arguments with lower complexity when ordered canonically in commutative functions.
- Additive functions: 1000-1999
- Multiplicative functions: 2000-2999
- Root and power functions: 3000-3999
- Log functions: 4000-4999
- Trigonometric functions: 5000-5999
- Hypertrigonometric functions: 6000-6999
- Special functions (factorial, Gamma, …): 7000-7999
- Collections: 8000-8999
- Inert and styling: 9000-9999
- Logic: 10000-10999
- Relational: 11000-11999
Default: 100,000
- hold: Hold;
"none"
Each of the arguments is evaluated (default)"all"
None of the arguments are evaluated and they are passed as is"first"
The first argument is not evaluated, the others are"rest"
The first argument is evaluated, the others aren’t"last"
: The last argument is not evaluated, the others are"most"
: All the arguments are evaluated, except the last one
Default:
"none"
- signature: FunctionSignature;
FunctionDefinitionFlags Permalink
A function definition can have some flags to indicate specific properties of the function.
- associative: boolean;
If
true
,["f", ["f", a], b]
simplifies to["f", a, b]
Default:
false
- commutative: boolean;
If
true
,["f", a, b]
equals["f", b, a]
. The canonical version of the function will order the arguments.Default:
false
- idempotent: boolean;
If
true
,["f", ["f", x]]
simplifies to["f", x]
.Default:
false
- inert: boolean;
An inert function evaluates directly to one of its argument, typically the first one. They may be used to provide formating hints, but do not affect simplification or evaluation.
Default: false
- involution: boolean;
If
true
,["f", ["f", x]]
simplifies tox
.Default:
false
- numeric: boolean;
All the arguments of a numeric function are numeric, and its value is numeric.
- pure: boolean;
If
true
, the value of this function is always the same for a given set of arguments and it has no side effects.An expression using this function is pure if the function and all its arguments are pure.
For example
Sin
is pure,Random
isn’t.This information may be used to cache the value of expressions.
Default:
true
- threadable: boolean;
If
true
, the function is applied element by element to lists, matrices (["List"]
or["Tuple"]
expressions) and equations (relational operators).Default:
false
FunctionEntry Permalink
A function is an identifier followed by:
- some postfix operators such as
\prime
- an optional list of arguments in an enclosure (parentheses)
For more complex situations, for example implicit arguments or
inverse functions postfix (i.e. ^{-1}), use a custom parse handler with a
entry of kind expression
.
- BaseEntry &
- Trigger &
- kind: "function";
- parse: Expression | FunctionParseHandler;
FunctionParseHandler Permalink
FunctionSignature Permalink
- domain: DomainExpression;
-
deprecated
The domain of this signature, a domain compatible with the
Functions
domain).deprecated
Use params, optParams, restParam and result instead
- evaluate: SemiBoxedExpression | (ce: IComputeEngine, args: BoxedExpression[]): BoxedExpression | undefined;
Evaluate a function expression.
The arguments have been evaluated, except the arguments to which a
hold
applied.It is not necessary to further simplify or evaluate the arguments.
If performing numerical calculations, if all the arguments are exact, return an exact expression. If any of the arguments is not exact, that is if it is a literal decimal (non-integer) number, return an approximation. In this case, the value may be the same as
expr.N()
.When doing an exact calculation:
- do not reduce rational numbers to decimal (floating point approximation)
- do not down convert bignums to machine numbers
- do not reduce square roots of rational numbers
- do not reduce constants with a
holdUntil
attribute of"N"
If the expression cannot be evaluated, due to the values, domains, or assumptions about its arguments, for example, return
undefined
or an["Error"]
expression.- optParams: DomainExpression[];
- params: DomainExpression[];
- restParam: DomainExpression;
- result: DomainExpression | (ce: IComputeEngine, args: BoxedDomain[]): BoxedDomain | null | undefined;
The domain of the result of the function. Either a domain expression, or a function that returns a boxed domain.
- N?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | BoxedExpression;
Evaluate numerically a function expression.
The arguments
args
have been simplified and evaluated, numerically if possible, except the arguments to which ahold
apply.The arguments may be a combination of numbers, symbolic expressions and other expressions.
Perform as many calculations as possible, and return the result.
Return
undefined
if there isn’t enough information to perform the evaluation, for example one of the arguments is a symbol with no value. If the handler returnsundefined
, symbolic evaluation of the expression will be returned instead to the caller.Return
NaN
if there is enough information to perform the evaluation, but a literal argument is out of range or not of the expected type.Use the value of
ce.numericMode
to determine how to perform the numeric evaluation.Note that regardless of the current value of
ce.numericMode
, the arguments may be boxed numbers representing machine numbers, bignum numbers, complex numbers, rationals or big rationals.If the numeric mode does not allow complex numbers (the
engine.numericMode
is not"complex"
or"auto"
) and the result of the evaluation would be a complex number, returnNaN
instead.If
ce.numericMode
is"bignum"
or"auto"
the evaluation should be done using bignums.Otherwise,
ce.numericMode
is `“machine”, the evaluation should be performed using machine numbers.You may perform any necessary computations, including approximate calculations on floating point numbers.
- canonical?: (ce: IComputeEngine, args: BoxedExpression[]): null | BoxedExpression;
Return the canonical form of the expression with the arguments
args
.The arguments (
args
) may not be in canonical form. If necessary, they can be put in canonical form.This handler should validate the domain and number of the arguments.
If a required argument is missing, it should be indicated with a
["Error", "'missing"]
expression. If more arguments than expected are present, this should be indicated with an [“Error”, “‘unexpected-argument’”]` error expressionIf the domain of an argument is not compatible, it should be indicated with an
incompatible-domain
error.["Sequence"]
expressions are not folded and need to be handled explicitly.If the function is associative, idempotent or an involution, this handler should account for it. Notably, if it is commutative, the arguments should be sorted in canonical order.
The handler can make transformations based on the value of the arguments that are exact and literal (i.e.
arg.numericValue !== null && arg.isExact
).Values of symbols should not be substituted, unless they have a
holdUntil
attribute of"never"
.The handler should not consider the value or any assumptions about any of the arguments that are symbols or functions (i.e.
arg.isZero
,arg.isInteger
, etc…) since those may change over time.The result of the handler should be a canonical expression.
If the arguments do not match, they should be replaced with an appropriate
["Error"]
expression. If the expression cannot be put in canonical form, the handler should returnnull
.- compile?: (expr: BoxedExpression): CompiledExpression;
Return a compiled (optimized) expression.
- evalDimension?: (ce: IComputeEngine, args: BoxedExpression[]): BoxedExpression;
-
experimental
Dimensional analysis
- sgn?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | 0 | 1 | -1;
Return the sign of the function expression.
- simplify?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | BoxedExpression;
Rewrite an expression into a simpler form.
The arguments are in canonical form and have been simplified.
The handler can use the values assigned to symbols and the assumptions about symbols, for example with
arg.numericValue
,arg.isInteger
orarg.isPositive
.Even though a symbol may not have a value, there may be some information about it reflected for example in
this.isZero
orthis.isPrime
.The handler should not perform approximate numeric calculations, such as calculations involving decimal numbers (non-integers). Making exact calculations on integers or rationals is OK.
Do not reduce constants with a
holdUntil
attribute of"N"
or"evaluate"
.This handler should not have any side-effects: do not modify the environment of the
ComputeEngine
instance, do not perform I/O, do not do calculations that depend on random values.If no simplification can be performed due to the values, domains or assumptions about its arguments, for example, return
undefined
.
Hold Permalink
- | "none"
- | "all"
- | "first"
- | "rest"
- | "last"
- | "most"
IdentifierDefinition Permalink
A table mapping identifiers to their definition.
Identifiers should be valid MathJSON identifiers. In addition, the following rules are recommended:
- Use only latin letters, digits and
-
:/[a-zA-Z0-9-]+/
- The first character should be a letter:
/^[a-zA-Z]/
- Functions and symbols exported from a library should start with an uppercase letter
/^[A-Z]/
If a semi boxed expression
IdentifierDefinitions Permalink
InfixEntry Permalink
- BaseEntry &
- Trigger &
- associativity: "right" | "left" | "non" | "both";
both
: a + b + c +(a, b, c)left
: a / b / c -> /(/(a, b), c)right
: a = b = c -> =(a, =(b, c))non
: a < b < c -> syntax error
- a
both
-associative operator has an unlimited number of arguments - a
left
,right
ornon
associative operator has at most two arguments
- kind: "infix";
Infix position, with an operand before and an operand after:
a ⊛ b
.Example:
+
,\times
.- parse: string | InfixParseHandler;
- precedence: Precedence;
InfixParseHandler Permalink
JsonSerializationOptions Permalink
Options to control the serialization to MathJSON when using BoxedExpression.json
.
- exclude: string[];
A list of space separated function names that should be excluded from the JSON output.
Those functions are replaced with an equivalent, for example,
Square
withPower
, etc…Possible values include
Sqrt
,Root
,Square
,Exp
,Subtract
,Rational
,Complex
Default:
[]
(none)- metadata: ("all" | "wikidata" | "latex")[];
A list of space separated keywords indicating which metadata should be included in the MathJSON. If metadata is included, shorthand notation is not used.
Default:
[]
(none)- precision: "auto" | "max" | number;
Number literals are serialized with this precision. If
"auto"
, the same precision as the compute engine calculations is used If"max"
, all available digits are serializedDefault:
"auto"
- repeatingDecimals: boolean;
If true, repeating decimals are detected and serialized accordingly For example:
1.3333333333333333
( \to )1.(3)
0.142857142857142857142857142857142857142857142857142
( \to )0.(1428571)
Default:
true
- shorthands: ("all" | "number" | "symbol" | "function" | "dictionary" | "string")[];
A list of space separated keywords indicating which MathJSON expressions can use a shorthand.
Default:
["all"]
LatexArgumentType Permalink
- | "{expression}"
- | "[expression]"
- | "{text}"
- | "[text]"
- | "{unit}"
- | "[unit]"
- | "{glue}"
- | "[glue]"
- | "{string}"
- | "[string]"
- | "{color}"
- | "[color]"
LatexDictionary Permalink
LatexDictionaryEntry Permalink
LatexString Permalink
A LaTeX string starts and end with $
, for example
"$\frac{\pi}{2}$"
.
LatexToken Permalink
A LatexToken
is a token as returned by Scanner.peek
.
It can be one of the indicated tokens, or a string that starts with a
\
for LaTeX commands, or a LaTeX character which includes digits,
letters and punctuation.
- | string
- | "<{>"
- | "<}>"
- | "<space>"
- | "<$>"
- | "<$$>"
LibraryCategory Permalink
- | "algebra"
- | "arithmetic"
- | "calculus"
- | "collections"
- | "control-structures"
- | "combinatorics"
- | "complex"
- | "core"
- | "data-structures"
- | "dimensions"
- | "domains"
- | "linear-algebra"
- | "logic"
- | "numeric"
- | "other"
- | "physics"
- | "polynomials"
- | "relop"
- | "sets"
- | "statistics"
- | "styling"
- | "symbols"
- | "trigonometry"
- | "units"
MatchfixEntry Permalink
- BaseEntry &
- closeTrigger: Delimiter | LatexToken[];
- kind: "matchfix";
- openTrigger: Delimiter | LatexToken[];
If
kind
is'matchfix'
: theopenTrigger
andcloseTrigger
properties are required.- parse: MatchfixParseHandler;
When invoked, the parser is pointing after the close delimiter. The argument of the handler is the body, i.e. the content between the open delimiter and the close delimiter.
MatchfixParseHandler Permalink
Metadata Permalink
Metadata that can be associated with a BoxedExpression
- latex: string;
- wikidata: string;
NumberFormattingOptions Permalink
- avoidExponentsInRange: undefined | null | [negativeExponent: number, positiveExponent: number];
- beginExponentMarker: LatexString;
- beginRepeatingDigits: LatexString;
- decimalMarker: LatexString;
A string representing the decimal marker, the string separating the whole portion of a number from the fractional portion, i.e. the ‘.’ in ‘3.1415’.
Some countries use a comma rather than a dot. In this case it is recommended to use
"{,}"
as the marker: the surrounding brackets ensure there is no additional gap after the comma.Default:
"."
- endExponentMarker: LatexString;
- endRepeatingDigits: LatexString;
- exponentProduct: LatexString;
- groupSeparator: LatexString;
A string representing the separator between groups of digits, used to improve readability of numbers with lots of digits.
If you change it to another value, be aware that this may lead to unexpected results. For example, if changing it to
,
the expression\operatorname{Hypot}(1,2)
will parse as["Hypot", 1.2]
rather than["Hypot", 1, 2]
.Default:
"\\,"
(thin space, 3/18mu) (Resolution 7 of the 1948 CGPM)- imaginaryUnit: LatexString;
- negativeInfinity: LatexString;
- notANumber: LatexString;
- notation: "engineering" | "auto" | "scientific";
- positiveInfinity: LatexString;
- precision: number;
- truncationMarker: LatexString;
NumericFlags Permalink
When used in a SymbolDefinition
, these flags are optional.
If provided, they will override the value derived from the symbol’s value.
For example, it might be useful to override algebraic = false
for a transcendental number.
- NaN: boolean | undefined;
- algebraic: boolean | undefined;
- complex: boolean | undefined;
- composite: boolean | undefined;
- even: boolean | undefined;
- extendedComplex: boolean | undefined;
- extendedReal: boolean | undefined;
- finite: boolean | undefined;
- imaginary: boolean | undefined;
- infinity: boolean | undefined;
- integer: boolean | undefined;
- negative: boolean | undefined;
- negativeOne: boolean | undefined;
- nonNegative: boolean | undefined;
- nonPositive: boolean | undefined;
- notZero: boolean | undefined;
- number: boolean | undefined;
- odd: boolean | undefined;
- one: boolean | undefined;
- positive: boolean | undefined;
- prime: boolean | undefined;
- rational: boolean | undefined;
- real: boolean | undefined;
- zero: boolean | undefined;
NumericMode Permalink
The numeric evaluation mode:
Mode | |
---|---|
"auto" |
Use bignum or complex numbers. |
"machine" |
IEEE 754-2008, 64-bit floating point numbers: 52-bit mantissa, about 15 digits of precision |
"bignum" |
Arbitrary precision floating point numbers, as provided by the “decimal.js” library |
"complex" |
Complex number represented by two machine numbers, a real and an imaginary part, as provided by the “complex.js” library |
- | "auto"
- | "machine"
- | "bignum"
- | "complex"
ParseLatexOptions Permalink
- parseArgumentsOfUnknownLatexCommands: boolean;
When an unknown LaTeX command is encountered, attempt to parse any arguments it may have.
For example,
\foo{x+1}
would produce['\foo', ['Add', 'x', 1]]
if this property is true,['LatexSymbols', '\foo', '<{>', 'x', '+', 1, '<{>']
otherwise.- parseNumbers: "auto" | "rational" | "decimal" | "never";
When parsing a decimal number (e.g.
3.1415
):"auto"
or"decimal"
: if a decimal number parse it as an approximate decimal number with a whole part and a fractional part"rational"
: if a decimal number, parse it as an exact rational number with a numerator and a denominator. If not a decimal number, parse it as a regular number."never"
: do not parse numbers, instead return each token making up the number (minus sign, digits, decimal marker, etc…).
Note: if the number includes repeating digits (e.g.
1.33(333)
), it will be parsed as a decimal number even if this setting is"rational"
.Default:
"auto"
- preserveLatex: boolean;
If true, the expression will be decorated with the LaTeX fragments corresponding to each elements of the expression.
The top-level expression, that is the one returned by
parse()
, will include the verbatim LaTeX input that was parsed. The sub-expressions may contain a slightly different LaTeX, for example with consecutive spaces replaced by one, with comments removed and with some low-level LaTeX commands replaced, for example\egroup
and\bgroup
.Default:
false
- skipSpace: boolean;
If true, ignore space characters in math mode.
Default:
true
- parseUnknownIdentifier: (identifier: string, parser: Parser): "symbol" | "function" | "unknown";
This handler is invoked when the parser encounters an identifier that does not have a corresponding entry in the dictionary.
The
identifier
argument is a valid identifier (see https://cortexjs.io/math-json/#identifiers for the definition of a valid identifier).The handler can return:
-
"symbol"
: the identifier is a constant or variable name. -
"function"
: the identifier is a function name. If an apply function operator (typically, parentheses) follow, they will be parsed as arguments to the function. -
"unknown"
: the identifier is not recognized.
-
PatternConditionFunction Permalink
PatternMatchOptions Permalink
Control how a pattern is matched to an expression.
substitution
: if present, assumes these values for the named wildcards, and ensure that subsequent occurence of the same wildcard have the same value.recursive
: if true, match recursively, otherwise match only the top level.numericTolerance
: if present, the tolerance for numeric comparison.exact
: if true, only match expressions that are structurally identical. If false, match expressions that are structurally identical or equivalent. For example, when false,["Add", '_a', 2]
matches2
, with a value of_a
of0
. If true, the expression does not match.
- exact: boolean;
- numericTolerance: number;
- recursive: boolean;
- substitution: BoxedSubstitution;
PatternReplaceFunction Permalink
PostfixEntry Permalink
- BaseEntry &
- Trigger &
- kind: "postfix";
Postfix position, with an operand before:
a ⊛
Example:
!
.- parse: PostfixParseHandler;
- precedence: Precedence;
PostfixParseHandler Permalink
Precedence Permalink
THEORY OF OPERATIONS
The precedence of an operator is a number that indicates the order in which operators are applied.
For example, in 1 + 2 * 3
, the *
operator has a higher precedence
than the +
operator, so it is applied first.
The precedence range from 0 to 1000. The larger the number, the higher the precedence, the more “binding” the operator is.
Here are some rough ranges for the precedence:
- 800: prefix and postfix operators:
\lnot
etc…POSTFIX_PRECEDENCE
= 810:!
,'
- 700: some arithmetic operators
EXPONENTIATION_PRECEDENCE
= 700:^
- 600: some binary operators
DIVISION_PRECEDENCE
= 600:\div
- 500: not used
- 400: not used
- 300: some logic and arithmetic operators:
\land
,\lor
,\times
, etc…MULTIPLICATION_PRECEDENCE
= 390:\times
- 200: arithmetic operators, inequalities:
ADDITION_PRECEDENCE
= 275:+
-
ARROW_PRECEDENCE
= 270:\to
\rightarrow
ASSIGNMENT_PRECEDENCE
= 260::=
COMPARISON_PRECEDENCE
= 245:\lt
\gt
- 241:
\leq
- 100: not used
- 0:
,
,;
, etc…
Some constants are defined below for common precedence values.
Note: MathML defines some operator precedence, but it has some issues and inconsistencies. However, whenever possible we adopted the MathML precedence. See https://www.w3.org/TR/2009/WD-MathML3-20090924/appendixc.html
For reference, the JavaScript operator precedence is documented here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence
PrefixEntry Permalink
- BaseEntry &
- Trigger &
- kind: "prefix";
Prefix position, with an operand after:
⊛ a
Example:
-
,\not
.- parse: PrefixParseHandler;
- precedence: Precedence;
PrefixParseHandler Permalink
Rational Permalink
- | [number, number]
- | [bigint, bigint]
ReplaceOptions Permalink
- iterationLimit: number;
If
iterationLimit
> 1, the rules will be repeatedly applied until no rules apply, up tomaxIterations
times.Note that if
once
is true,maxIterations
has no effect.Default:
1
- once: boolean;
If
true
, stop after the first rule that matches.If
false
, apply all the remaining rules even after the first match.Default:
true
- recursive: boolean;
If
true
, apply replacement rules to all sub-expressions. Iffalse
, only consider the top-level expression.Default:
true
Rule Permalink
A rule describes how to modify an expressions that matches a pattern match
into a new expression replace
.
x-1
( \to ) 1-x
(x+1)(x-1)
( \to ) `x^2-1
The match
pattern can be expressed as a LaTeX string or a MathJSON expression.
Anonymous wildcards (_
) will match any
expression. Named wildcards (_x
, _a
, etc…) will match any expression
and bind the expression to the wildcard name.
In addition the sequence wildcard (__1
, __a
, etc…) will match a sequence
of one or more expressions, and bind the sequence to the wildcard name.
- condition: LatexString | PatternConditionFunction;
- id: string;
- match: LatexString | SemiBoxedExpression | Pattern;
- priority: number;
- replace: LatexString | SemiBoxedExpression | PatternReplaceFunction;
RuntimeIdentifierDefinitions Permalink
The entries have been validated and optimized for faster evaluation.
When a new scope is created with pushScope()
or when creating a new
engine instance, new instances of this type are created as needed.
RuntimeScope Permalink
- Scope &
- assumptions: undefined | ExpressionMapInterface<boolean>;
- ids: RuntimeIdentifierDefinitions;
- parentScope: RuntimeScope;
Scope Permalink
A scope is a set of names in a dictionary that are bound (defined) in a MathJSON expression.
Scopes are arranged in a stack structure. When an expression that defined a new scope is evaluated, the new scope is added to the scope stack. Outside of the expression, the scope is removed from the scope stack.
The scope stack is used to resolve symbols, and it is possible for a scope to ‘mask’ definitions from previous scopes.
Scopes are lexical (also called a static scope): they are defined based on where they are in an expression, they are not determined at runtime.
- iterationLimit: number;
-
experimental
Signal
iteration-limit-exceeded
when the iteration limit in a loop is exceeded. Default: no limits. - memoryLimit: number;
-
experimental
Signal
out-of-memory
when the memory usage for this scope is exceeded.Memory is in Megabytes, default: 1Mb.
- recursionLimit: number;
-
experimental
Signal
recursion-depth-exceeded
when the recursion depth for this scope is exceeded. - timeLimit: number;
-
experimental
Signal
timeout
when the execution time for this scope is exceeded.Time in seconds, default 2s.
SemiBoxedExpression Permalink
A semi boxed expression is an MathJSON expression which can include some boxed terms.
This is convenient when creating new expressions from portions
of an existing BoxedExpression
while avoiding unboxing and reboxing.
- | number
- | string
- | Decimal
- | Complex
- | MathJsonNumber
- | MathJsonString
- | MathJsonSymbol
- | MathJsonFunction
- | MathJsonDictionary
- | SemiBoxedExpression[]
- | BoxedExpression
SerializeHandler Permalink
SerializeLatexOptions Permalink
- invisibleMultiply: LatexString;
LaTeX string used to render an invisible multiply, e.g. in ‘2x’.
Leave it empty to join the adjacent terms, i.e.
2x
.Use
\cdot
to insert a\cdot
operator between them, i.e.2\cdot x
.Empty by default.
- invisiblePlus: LatexString;
LaTeX string used for an invisible plus with mixed numbers e.g. in ‘1 3/4’.
Leave it empty to join the main number and the fraction, i.e. render it as
1\frac{3}{4}
.Use
+
to insert an explicit+
operator between them, i.e.1+\frac{3}{4}
Empty by default.
- missingSymbol: LatexString;
When an expression contains the error expression
["Error", 'missing']
, serialize it with this LaTeX string- multiply: LatexString;
LaTeX string used for an explicit multiply operator,
Default:
\times
- applyFunctionStyle: (expr: Expression, level: number): DelimiterScale;
- fractionStyle: (expr: Expression, level: number): "quotient" | "block-quotient" | "inline-quotient" | "inline-solidus" | "nice-solidus" | "reciprocal" | "factor";
- groupStyle: (expr: Expression, level: number): DelimiterScale;
- logicStyle: (expr: Expression, level: number): "boolean" | "word" | "uppercase-word" | "punctuation";
- numericSetStyle: (expr: Expression, level: number): "compact" | "regular" | "interval" | "set-builder";
- powerStyle: (expr: Expression, level: number): "quotient" | "solidus" | "root";
- rootStyle: (expr: Expression, level: number): "radical" | "quotient" | "solidus";
SimplifyOptions Permalink
Options for BoxedExpression.simplify()
- recursive: boolean;
- rules: BoxedRuleSet;
Substitution Permalink
A substitution describes the values of the wildcards in a pattern so that the pattern is equal to a target expression.
A substitution can also be considered a more constrained version of a
rule whose lhs
is always a symbol.
- [symbol: string]: T}
SymbolAttributes Permalink
- constant: boolean;
If
true
the value of the symbol is constant. The value or domain of symbols with this attribute set totrue
cannot be changed.If
false
, the symbol is a variable.Default:
false
- holdUntil: "never" | "simplify" | "evaluate" | "N";
If the symbol has a value, it is held as indicated in the table below. A green checkmark indicate that the symbol is substituted.
| Operation |
"never"
|"simplify"
|"evaluate"
|"N"
| | :— | :----- | |canonical()
| (X) | | | | |simplify()
| (X) | (X) | | | |evaluate()
| (X) | (X) | (X) | | |"N()"
| (X) | (X) | (X) | (X) |Some examples:
i
hasholdUntil: 'never'
GoldenRatio
hasholdUntil: 'simplify'
(symbolic constant)x
hasholdUntil: 'evaluate'
(variables)Pi
hasholdUntil: 'N'
(special numeric constant)
Default:
evaluate
SymbolDefinition Permalink
A bound symbol (i.e. one with an associated definition) has either a domain (e.g. ∀ x ∈ ℝ), a value (x = 5) or both (π: value = 3.14… domain = TranscendentalNumbers)
- BaseDefinition &
- Partial<SymbolAttributes> &
- domain: DomainLiteral | BoxedDomain;
- flags: Partial<NumericFlags>;
- inferred: boolean;
If true, the domain is inferred, and could be adjusted later as more information becomes available or if the symbol is explicitly declared.
- value: LatexString | SemiBoxedExpression | (ce: IComputeEngine): SemiBoxedExpression | null;
value
can be a JS function since for some constants, such asPi
, the actual value depends on theprecision
setting of theComputeEngine
and possible other environment settings
SymbolEntry Permalink
- BaseEntry &
- Trigger &
- kind: "symbol";
- parse: Expression | SymbolParseHandler;
- precedence: Precedence;
Used for appropriate wrapping (i.e. when to surround it with parens)
SymbolParseHandler Permalink
Terminator Permalink
This indicates a condition under which parsing should stop:
- an operator of a precedence higher than specified has been encountered
- the last token has been reached
- or if a condition is provided, the condition returns true;
- minPrec: Precedence;
- condition?: (parser: Parser): boolean;
Trigger Permalink
The trigger is the set of tokens that will make this record eligible to
parse the stream and generate an expression. If the trigger matches,
the parse
handler is called, if available.
The trigger can be specified either as a LaTeX string (latexTrigger
) or
as an identifier (identifierTrigger
), which can be wrapped in a LaTeX
command, for example \operatorname{mod}
or \mathbin{gcd}
, with "gcd"
being the identifierTrigger
.
matchfix
operators use openTrigger
and closeTrigger
instead.
- identifierTrigger: string;
- latexTrigger: LatexString | LatexToken[];
grok