Compute Engine

module compute-engineClasses

interface BoxedBaseDefinition

interface BoxedBaseDefinitionProperties / Methods

interface BoxedBaseDefinitiondescription

  • | string
  • | string[]

interface BoxedBaseDefinitionname: string

interface BoxedBaseDefinitionreset()

reset(): any

When the environment changes, for example the numerical precision, call reset() so that any cached values can be recalculated.

interface BoxedBaseDefinitionscope: undefined | RuntimeScope

The scope this definition belongs to.

This field is usually undefined, but its value is set by getDefinition()

interface BoxedBaseDefinitionurl: string

interface BoxedBaseDefinitionwikidata: string

interface BoxedDomain

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 BoxedDomainis()

is(s: BoxedDomain): boolean

From Object.is(). Equivalent to BoxedExpression.isSame()

interface BoxedDomainisCompatible()

isCompatible(dom: string | BoxedDomain, kind?: DomainCompatibility): boolean

True if a valid domain, and compatible with dom

interface BoxedDomainisFunction: boolean

interface BoxedDomainisNothing: boolean

If this is the Nothing symbol, return true.

Note applicable to canonical and non-canonical expressions.

interface BoxedDomainisNumeric: boolean

interface BoxedDomainisRelationalOperator: boolean

The function represent a relation between the first argument and the second argument, and evaluates to a boolean indicating if the relation is satisfied.

For example, Equal, Less, Approx, etc…

Default: false

interface BoxedDomaincanonical: BoxedDomain  read only

interface BoxedDomaincodomain: null | BoxedDomain  read only

interface BoxedDomainctor: null | DomainConstructor  read only

interface BoxedDomaindomainArg1: null | BoxedExpression | DomainExpression<BoxedExpression>  read only

interface BoxedDomaindomainArgs: null | (BoxedExpression | DomainExpression<BoxedExpression>)[]  read only

interface BoxedDomainjson: Expression  read only

interface BoxedDomainliteral: null | string  read only

Primitive Methods

Relational Operator

interface BoxedExpression

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()

getKey(key: string): undefined | BoxedExpression

If this expression is a dictionary, return the value of the key entry.

interface BoxedExpressionhasKey()

hasKey(key: string): boolean

If this expression is a dictionary, return true if the dictionary has a key entry.

interface BoxedExpressionkeys

  • | null
  • | IterableIterator<string>

The keys of the dictionary.

If this expression not a dictionary, return null

interface BoxedExpressionkeysCount: number

Domain Properties

interface BoxedExpressionisAlgebraic: undefined | boolean

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

The value of this expression is a number, but not NaN or any Infinity

isReal || isImaginary

interface BoxedExpressionisExtendedComplex: undefined | boolean

isReal || isImaginary || isInfinity

interface BoxedExpressionisExtendedReal: undefined | boolean

Real or ±Infinity

isReal || isInfinity

interface BoxedExpressionisImaginary: undefined | boolean

The value of this expression is a number with a imaginary part

interface BoxedExpressionisInteger: undefined | boolean

The value of this expression is an element of the set ℤ: …,-2, -1, 0, 1, 2…

interface BoxedExpressionisNumber: undefined | boolean

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

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

The value of this expression is real number: finite and not imaginary.

isFinite && !isImaginary

Expression Properties

interface BoxedExpressionisComposite: undefined | boolean

interface BoxedExpressionisEven: undefined | boolean

interface BoxedExpressionisFinite: undefined | boolean

This expression is a number, but not ±Infinity and not NaN

interface BoxedExpressionisInfinity: undefined | boolean

The numeric value of this expression is ±Infinity or Complex Infinity

interface BoxedExpressionisNaN: undefined | boolean

“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

The numeric value of this expression is < 0, same as isLess(0)

interface BoxedExpressionisNegativeOne: undefined | boolean

The numeric value of this expression is not -1.

interface BoxedExpressionisNonNegative: undefined | boolean

The numeric value of this expression is >= 0, same as isGreaterEqual(0)

interface BoxedExpressionisNonPositive: undefined | boolean

The numeric value of this expression is <= 0, same as isLessEqual(0)

interface BoxedExpressionisNotZero: undefined | boolean

The numeric value of this expression is not 0.

interface BoxedExpressionisOdd: undefined | boolean

interface BoxedExpressionisOne: undefined | boolean

The numeric value of this expression is not 1.

interface BoxedExpressionisPositive: undefined | boolean

The numeric value of this expression is > 0, same as isGreater(0)

interface BoxedExpressionisPrime: undefined | boolean

interface BoxedExpressionisZero: undefined | boolean

The numeric value of this expression is 0.

Function Expression

interface BoxedExpressionnops: number

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

First operand, i.e.this.ops[0]

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionop2: BoxedExpression

Second operand, i.e.this.ops[1]

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionop3: BoxedExpression

Third operand, i.e. this.ops[2]

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionops

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

  • | 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.

interface BoxedExpressionsgn

  • | undefined
  • | null
  • | 0
  • | 1
  • | -1

Return the following, depending on the value of this expression:

  • -1 if it is < 0
  • 0 if it is = 0
  • +1 if it is > 0
  • undefined 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

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

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

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()

N(options?: NOptions): BoxedExpression

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 BoxedExpressionapply()

apply(fn: (x: BoxedExpression): SemiBoxedExpression, head?: string): BoxedExpression

If this expression is a function, apply the function fn to all its operands.

Replace the head of this expression with head, if defined.

If this expression is a dictionary, return a new dictionary with the values modified by fn.

If head is provided, return a function expression with the modified dictionary as operand, otherwise return the modified dictionary.

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionbasedDefinition: undefined | BoxedBaseDefinition

For symbols and functions, a possible definition associated with the expression. basedDefinition is the base class of symbol and function definition.

Note undefined if not a canonical expression.

interface BoxedExpressioncomplexity: undefined | number

Expressions with a higher complexity score are sorted first in commutative functions

Note undefined if not a canonical expression.

interface BoxedExpressiondescription

  • | undefined
  • | string[]

An optional short description if the symbol or function head.

May include markdown. Each string is a paragraph.

Note undefined if not a canonical expression.

interface BoxedExpressionengine: IComputeEngine

The Compute Engine associated with this expression provides a context in which to interpret it, such as definition of symbols and functions.

interface BoxedExpressionerrors: BoxedExpression[]

All the ["Error"] subexpressions

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionevaluate()

evaluate(options?: EvaluateOptions): BoxedExpression

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 BoxedExpressionexplicitDomain: undefined | BoxedDomain

The domain of this expression, without accounting for any inferred domain or ce.defaultDomain. If no domain has been explicitly set via assignment or via an .assume() directive, the expr.explicitDomain is undefined.

This is useful to determine if the domain of an expression is inferred.

In most cases you’ll want to use expr.domain instead.

Note undefined if not a canonical expression or not a function.

interface BoxedExpressionfreeVars: string[]

All the free variables in the expression, recursively, that is all the symbols with no value

interface BoxedExpressionfunctionDefinition: undefined | BoxedFunctionDefinition

For functions, a possible definition associated with the expression.

Note undefined if not a canonical expression or not a function.

interface BoxedExpressiongetSubexpressions()

getSubexpressions(head: string): BoxedExpression[]

All the subexpressions matching the head

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionhas()

has(v: string | string[]): boolean

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

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

True if the expression is a constant, that is a symbol with an immutable value

interface BoxedExpressionisExact: boolean

An exact value is not further transformed when evaluated. To get an approximate evaluation of an exact value, use .N().

Non-exact values includes:

  • numbers with a fractional part
  • complex numbers with a real or imaginary fractional part

interface BoxedExpressionisFree: boolean

True if the expression is a free variable, that is a symbol with no value

interface BoxedExpressionisNothing: boolean

If this is the Nothing symbol, return true.

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionisPure: boolean

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

MathJSON representation of this expression.

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionmatch()

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 BoxedExpressionreplace()

replace(rules: BoxedRuleSet, options?: ReplaceOptions): null | BoxedExpression

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

The scope in which this expression has been defined. Is null when the expression is not canonical.

interface BoxedExpressionsimplify()

simplify(options?: {recursive: boolean; rules: BoxedRuleSet}): BoxedExpression

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()

solve(vars: Iterable<string>): null | BoxedExpression[]

interface BoxedExpressionsubexpressions: BoxedExpression[]

All the subexpressions in this expression, recursively

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionsubs()

subs(sub: Substitution<SemiBoxedExpression>, options?: {canonical: boolean}): BoxedExpression

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

For symbols, a possible definition associated with the expression.

Note undefined if not a symbol

interface BoxedExpressionsymbols: string[]

All the symbols in the expression, recursively

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionurl: undefined | string

An optional URL pointing to more information about the symbol or function head

Note undefined if not a canonical expression.

interface BoxedExpressioncanonical: BoxedExpression  read only

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

get domain(): BoxedDomain

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.

Note: If non-canonical, return the domain of its canonical counterpart

Modify the domain of a symbol that represent a variable (or a function name).

Note: If non-canonical, does nothing.

interface BoxedExpressionisCanonical: boolean

If true, this expression is in a canonical form.

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionlatex: string

LaTeX representation of this expression.

The serialization can be customized with ComputeEngine.latexOptions

Note applicable to canonical and non-canonical expressions.

interface BoxedExpressionvalue

get value(): undefined | BoxedExpression
set value(undefined | number | BoxedExpression)

Synonym for evaluate(). If the expression is pure, the value may be cached.

It returns undefined for expressions that are not pure or that may not be evaluated.

Note: If non-canonical, return the value of its canonical counterpart

Only the value of variables can be changed (symbols that are not constants).

Note: If non-canonical, does nothing.

interface BoxedExpressionwikidata: undefined | string

Wikidata identifier.

Note undefined if not a canonical expression.

Primitive Methods

interface BoxedExpression[toPrimitive]()

[toPrimitive](hint: "string" | "number" | "default"): null | string | number

Similar toexpr.valueOf() but includes a hint.

interface BoxedExpressionis()

is(rhs: unknown): boolean

From Object.is(). Equivalent to BoxedExpression.isSame()

interface BoxedExpressiontoJSON()

toJSON(): Expression

Used by JSON.stringify() to serialize this object to JSON.

Method version of expr.json.

interface BoxedExpressiontoString()

toString(): string

From Object.toString(), return a LaTeX representation of the expression.

Used when coercing a BoxedExpression to a String.

interface BoxedExpressionvalueOf()

valueOf(): string | number | boolean

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 number.

If the expression is a symbol, return the name of the symbol as a string.

Otherwise return a LaTeX representation of the expression.

Relational Operator

interface BoxedExpressionisEqual()

isEqual(rhs: BoxedExpression): boolean

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()

isGreater(rhs: BoxedExpression): undefined | boolean

The numeric value of both expressions are compared.

interface BoxedExpressionisGreaterEqual()

isGreaterEqual(rhs: BoxedExpression): undefined | boolean

The numeric value of both expressions are compared.

interface BoxedExpressionisLess()

isLess(rhs: BoxedExpression): undefined | boolean

If the expressions cannot be compared, return undefined

The numeric value of both expressions are compared.

interface BoxedExpressionisLessEqual()

isLessEqual(rhs: BoxedExpression): undefined | boolean

The numeric value of both expressions are compared.

interface BoxedExpressionisSame()

isSame(rhs: BoxedExpression): boolean

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

interface BoxedSymbolDefinitionProperties / Methods

interface BoxedSymbolDefinitionat()

at(index: string | number): undefined | BoxedExpression

interface BoxedSymbolDefinitiondomain: undefined | BoxedDomain

interface BoxedSymbolDefinitionvalue

get value(): undefined | BoxedExpression
set value(undefined | SemiBoxedExpression)

interface ComputeEngineStats

expressions: null | Set<BoxedExpression>
highwaterMark: number
symbols: Set<BoxedExpression>

interface ExpressionMapInterface

[iterator](): IterableIterator<[BoxedExpression, U]>
clear(): void
delete(expr: BoxedExpression): void
get(expr: BoxedExpression): undefined | U
has(expr: BoxedExpression): boolean
set(expr: BoxedExpression, value: U): void

class LatexSyntax

To customize the parsing and serializing of LaTeX syntax, create a LatexSyntax instance.

class LatexSyntaxnew LatexSyntax()

new LatexSyntax(options?: NumberFormattingOptions & ParseLatexOptions & SerializeLatexOptions & {dictionary: LatexDictionary; onError: WarningSignalHandler}): LatexSyntax

class LatexSyntaxMethods / Properties

class LatexSyntaxgetDictionary()

getDictionary(domain?: LibraryCategory | "all"): readonly LatexDictionaryEntry[]

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()

parse(latex: string): Expression

class LatexSyntaxserialize()

serialize(expr: Expression): string

interface Parser

interface ParserProperties / Methods

interface ParseraddBoundary()

addBoundary(boundary: string[]): void

interface ParserapplyInvisibleOperator()

applyInvisibleOperator(terminator: Terminator, lhs: null | Expression): null | Expression

interface ParseratEnd: boolean

True if the last token has been reached

interface ParseratTerminator()

atTerminator(t: Terminator): boolean

Return true if the terminator condition is met

interface ParserboundaryError()

boundaryError(msg: string | [string, ...Expression[]]): Expression

interface ParsercomputeEngine: IComputeEngine

interface Parsererror()

error(code, fromToken)
code:
  • | string
  • | [string, ...Expression[]]
fromToken: number
Expression

Return an error expression with the specified code and arguments

interface Parserindex: number

interface ParserlatexAfter()

latexAfter(): string

Return a LaTeX string after the index

interface ParserlatexBefore()

latexBefore(): string

Return a LaTeX string before the index

interface ParserlookAhead()

lookAhead(): string[]

Return an array of string corresponding to tokens ahead. The index is unchanged.

interface Parsermatch()

match(tokens: string): boolean

If the next token matches the target advance and return true. Otherwise return false

interface ParsermatchAll()

matchAll(tokens: string | string[]): boolean

interface ParsermatchAny()

matchAny(tokens: string[]): string

interface ParsermatchArguments()

matchArguments(kind: "" | "implicit" | "enclosure"): null | Expression[]
  • ‘enclosure’ : will look for an argument inside an enclosure (an open/close fence)
  • ‘implicit’: either an expression inside a pair of (), or just a primary (i.e. we interpret \cos x + 1 as \cos(x) + 1)

interface ParsermatchBoundary()

matchBoundary(): boolean

interface ParsermatchChar()

matchChar(): null | string

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 ParsermatchColor()

matchColor(background?: boolean): null | string

Return a CSS color. Handle the various color formats supported by the xcolor package.

interface ParsermatchDecimalDigits()

matchDecimalDigits(): string

interface ParsermatchExponent()

matchExponent(): string

interface ParsermatchExpression()

matchExpression(until?: Partial<Terminator>): null | Expression

Parse an expression:

<expression> ::=
 | <prefix-op> <expression>
 | <primary>
 | <primary> <infix-op> <expression>

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 ParsermatchLatexDimension()

matchLatexDimension(): null | string

Return a LaTeX dimension.

interface ParsermatchMiddleDelimiter()

matchMiddleDelimiter(delimiter: string): boolean

interface ParsermatchNumber()

matchNumber(): string

interface ParsermatchOpenDelimiter()

matchOpenDelimiter(openDelim: Delimiter, closeDelim: Delimiter): null | string[]

If matches the normalized open delimiter, returns the expected closing delimiter.

For example, if openDelim is (, and closeDelim is ) it would match \left\lparen and return ['\right', '\rparen'], which can be matched with matchAll()

interface ParsermatchOptionalLatexArgument()

matchOptionalLatexArgument(): null | Expression

If the next tokens correspond to an optional LaTeX argument, enclosed with [ and ] return the content of the argument as an expression and advance the index past the closing ].

Otherwise, return null.

interface ParsermatchOptionalSign()

matchOptionalSign(): string

If the next token matches a + or - sign, return it and advance the index. Otherwise return '' and do not advance

interface ParsermatchPrimary()

matchPrimary(): null | Expression
   <primary> :=
      (<number> | <symbol> | <latex-command> | <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>

If not a primary, return null and do not advance the index.

interface ParsermatchRequiredLatexArgument()

matchRequiredLatexArgument(excluding?: string[]): null | Expression

Match a required LaTeX argument:

  • either enclosed in {}
  • or a single token (except if token is in excluding)

The excluding option is useful 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.

If none is provided, excluding is !"#$%&(),/;:[email protected][]|~", \left and \bigl

Return null if no argument was found Return ['Sequence'] if an empty argument {} was found

interface ParsermatchSequence()

matchSequence(tokens: string[]): string[]

interface ParsermatchSignedInteger()

matchSignedInteger(): string

interface ParsermatchStringArgument()

matchStringArgument(): null | string

interface ParsermatchSupsub()

matchSupsub(lhs: null | Expression): null | Expression

Match a sequence superfix/subfix operator, e.g. ^{*}

Superfix and subfix need special handling:

  • they act mostly like an infix operator, but they are commutative, i.e. x_a^b should be parsed identically to x^b_a.

  • furthermore, in LaTeX x^a^b parses the same as x^a{}^b.

interface ParsermatchSymbol()

matchSymbol(): null | Expression

A symbol can be:

  • a single-letter variable: x
  • a single LaTeX command: \pi

interface ParsermatchTabular()

matchTabular(endName: string): null | Expression[][]

Parse a tabular environment, until \end{endName}

interface Parsernext()

next(): string

Return the next token and advance the index

interface Parseroptions: Required<ParseLatexOptions>

interface Parserpeek: string

Return the next token, without advancing the index

interface ParserremoveBoundary()

removeBoundary(): void

interface ParserskipSpace()

skipSpace(): boolean

If there are any space, advance the index until a non-space is encountered

interface Pattern

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()

count(exprs: Iterable<BoxedExpression>, options?: PatternMatchOptions): number

Return the number of exprs that matched the pattern

interface Patterntest()

test(expr: BoxedExpression, options?: PatternMatchOptions): boolean

If expr matches the pattern, return true, otherwise false

Primitive Methods

Relational Operator

interface Serializer

interface SerializerProperties / Methods

interface SerializerapplyFunctionStyle()

applyFunctionStyle(expr: Expression, level: number): "paren" | "leftright" | "big" | "none"

Styles

interface SerializerfractionStyle()

fractionStyle(expr: Expression, level: number): "quotient" | "inline-solidus" | "nice-solidus" | "reciprocal" | "factor"

interface SerializergroupStyle()

groupStyle(expr: Expression, level: number): "paren" | "leftright" | "big" | "none"

interface Serializerlevel: number

“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()

logicStyle(expr: Expression, level: number): "boolean" | "word" | "uppercase-word" | "punctuation"

interface SerializernumericSetStyle()

numericSetStyle(expr: Expression, level: number): "compact" | "regular" | "interval" | "set-builder"

interface SerializeronError: WarningSignalHandler

interface Serializeroptions: Required<SerializeLatexOptions>

interface SerializerpowerStyle()

powerStyle(expr: Expression, level: number): "quotient" | "solidus" | "root"

interface SerializerrootStyle()

rootStyle(expr: Expression, level: number): "radical" | "quotient" | "solidus"

interface Serializerserialize()

serialize(expr: null | Expression): string

Output a LaTeX string representing the expression

interface Serializerwrap()

wrap(expr: null | Expression, prec?: number): string

Add a group fence around the expression if it is an operator of precedence less than or equal to prec.

interface SerializerwrapArguments()

wrapArguments(expr: Expression): string

A string with the arguments of expr fenced appropriately and separated by commas.

interface SerializerwrapShort()

wrapShort(expr: null | Expression): string

Add a group fence around the expression if it is short (not a function)

interface SerializerwrapString()

wrapString(s, style, fence?)
s: string
style:
  • | "paren"
  • | "leftright"
  • | "big"
  • | "none"
fence?: string
string

version

version: ""

module compute-engineTypes

AssumeResult

  • | "internal-error"
  • | "not-a-predicate"
  • | "contradiction"
  • | "tautology"
  • | "ok"

BaseDefinition

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 the Pi constant.

BaseEntry

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 a parse handler.

An entry with no name cannot be serialized: the name is used to map a MathJSON function or symbol name to the appropriate entry for serializing. However, an entry with no name can be used to define a synonym (for example for the symbol \varnothing which is a synonym for \emptyset).

If not parse handler is provided, only the trigger is used to select this entry. Otherwise, if the trigger of the entry matches the current token, the parse handler is invoked.

serialize: LatexString | SerializeHandler;

Transform an expression into a LaTeX string. If no serialize handler is provided, the trigger property is used

trigger: LatexString | LatexToken[];

The trigger is the set of tokens that will make this record eligible for attempting to parse the stream and generate an expression. After the trigger matches, the parse handler is called, if available.

matchfix operators use openDelimiter and closeDelimiter instead.

BoxedFunctionDefinition

BoxedFunctionSignature

codomain: BoxedDomain | (ce: IComputeEngine, args: BoxedExpression[]): BoxedDomain | null;
domain: BoxedDomain;
evaluate: BoxedExpression | (ce: IComputeEngine, args: BoxedExpression[]): BoxedExpression | 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;
sgn?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | 0 | 1 | -1;
simplify?: (ce: IComputeEngine, args: BoxedExpression[]): undefined | BoxedExpression;

BoxedRule

[lhs: Pattern, rhs: BoxedExpression, priority: number, condition: undefined | (wildcards: BoxedSubstitution): boolean]

BoxedRuleSet

BoxedSubstitution

CompiledExpression

evaluate?: (scope: {[symbol: string]: BoxedExpression}): number | BoxedExpression;

DefaultEntry

A simple LaTeX dictionary entry, for example for a command like \pi.


Delimiter

Open and close delimiters that can be used with MatchfixEntry record to define new LaTeX dictionary entries.


  • | ")"
  • | "("
  • | "]"
  • | "["
  • | "{"
  • | "}"
  • | "<"
  • | ">"
  • | "|"
  • | "||"
  • | "\lceil"
  • | "\rceil"
  • | "\lfloor"
  • | "\rfloor"

DomainCompatibility

  • | "covariant"
  • | "contravariant"
  • | "bivariant"
  • | "invariant"

DomainConstructor

A domain constructor is the head of a domain expression.


  • | "Error"
  • | "Matrix"
  • | "SquareMatrix"
  • | "Vector"
  • | "Function"
  • | "List"
  • | "Dictionary"
  • | "Tuple"
  • | "Range"
  • | "Interval"
  • | "Intersection"
  • | "Union"
  • | "Maybe"
  • | "Sequence"
  • | "Head"
  • | "Symbol"
  • | "Value"
  • | "Covariant"
  • | "Contravariant"
  • | "Bivariant"
  • | "Invariant"

DomainExpression

<T> =

DomainLiteral

string

EnvironmentEntry

A LaTeX dictionary entry for an environment, that is a LaTeX construct using \begin{...}...\end{...}.


EnvironmentParseHandler

(parser: Parser, reqArgs: Expression[], optArgs: Expression[]): Expression | null

FunctionDefinition

Definition record for a function.


  • BaseDefinition &
  • 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: "none" | "all" | "first" | "rest" | "last" | "most";
    • "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

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 to x.

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

  • BaseEntry &
  • kind: "function";
    parse: Expression | FunctionParseHandler;

    Indicate if this symbol can be followed by arguments.

    The presence of arguments will indicate that the arguments should be applied to the symbol. Otherwise, the invisible operator is applied to the symbol and the arguments.

    If arguments is "group":

    “f(x)” -> ["f", "x"] “f x” -> ["Multiply", "f", "x"]

    If arguments is "":

    “f(x)” -> ["Multiply", "f", "x"] “f x” -> ["Multiply", "f", "x"]

    If arguments is "implicit" and the symbol is followed either by a group or by a primary (prefix + symbol + subsupfix + postfix). Used for trig functions. i.e. \sin x vs \sin(x):

    “f(x)” -> ["f", "x"] “f x” -> ["f", "x"]

FunctionParseHandler

(parser: Parser): Expression | null

FunctionSignature

domain: BoxedDomain | DomainExpression;

The domain of this signature, a domain compatible with the Function domain)

evaluate: SemiBoxedExpression | (ce: IComputeEngine, args: BoxedExpression[]): BoxedExpression | undefined;

Evaluate symbolically a function expression.

The arguments have been symbolically evaluated, except the arguments to which a hold apply.

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 hold attribute

If the expression cannot be evaluated, due to the values, domains, or assumptions about its arguments, for example, return undefined or an ["Error"] expression.

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 a hold 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 returns undefined, 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.

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.

Use the value of ce.numericMode to determine how to perform the numeric evaluation.

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, return NaN 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 a unexpected-argument error. If the domain of an argument is not compatible, it should be indicated with a 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.

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 return null.

codomain?: (ce: IComputeEngine, args: BoxedDomain[]): null | BoxedDomain;

An optional handler to determine the codomain of the function. If not provided, the codomain of the function is determined from domain

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 or arg.isPositive.

Even though a symbol may not have a value, there may be some information about it reflected for example in this.isZero or this.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.

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.

IdTable

An ID table contains definitions for symbols and functions.

The index of the table is an identifier, the name of the symbol or function for this definition

The name of a symbol or function is an arbitrary string of Unicode characters, however the following conventions are recommended:

  • Use only 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]/

InfixEntry

  • BaseEntry &
  • 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 or non 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: number;

InfixParseHandler

(parser: Parser, until: Terminator, lhs: Expression): Expression | null

JsonSerializationOptions

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 with Power, 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 serialized

Default: "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

  • | "{expression}"
  • | "[expression]"
  • | "{text}"
  • | "[text]"
  • | "{unit}"
  • | "[unit]"
  • | "{glue}"
  • | "[glue]"
  • | "{string}"
  • | "[string]"
  • | "{color}"
  • | "[color]"

LatexDictionary

LatexDictionaryEntry

LatexString

A LaTeX string starts and end with $, for example "$\frac{\pi}{2}$".


string

LatexToken

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

  • | "algebra"
  • | "arithmetic"
  • | "calculus"
  • | "collections"
  • | "control-structures"
  • | "combinatorics"
  • | "core"
  • | "data-structures"
  • | "dimensions"
  • | "domains"
  • | "linear-algebra"
  • | "logic"
  • | "numeric"
  • | "other"
  • | "physics"
  • | "polynomials"
  • | "relop"
  • | "sets"
  • | "statistics"
  • | "styling"
  • | "symbols"
  • | "trigonometry"
  • | "units"

MatchfixEntry

  • BaseEntry &
  • closeDelimiter: Delimiter | LatexToken[];
    kind: "matchfix";
    openDelimiter: Delimiter | LatexToken[];

    If kind is 'matchfix': the closeDelimiter and openDelimiter property 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

(parser: Parser, body: Expression): Expression | null

Metadata

Metadata that can be associated with a BoxedExpression


latex: string;
wikidata: string;

NumberFormattingOptions

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 \mathrm{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;

NumericMode

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"

ParseHandler

ParseLatexOptions

applyInvisibleOperator: "auto" | null | (parser: Parser, lhs: Expression, rhs: Expression): Expression | null;

This function is invoked when a number is followed by a symbol, an open delimiter or a function.

If this function is set to null, the lhs and rhs are joined as a Sequence.

If this function is set to undefined it behaves in the following way:

  • a number followed by a numeric expression is considered as separated with an invisible multiplication sign, and the two are joined as [‘Multiply’, lhs, rhs].
  • a number followed by a rational number is considered to be separated with an invisible plus, and the two are joined as [‘Add’, lhs,

For example with 2\frac{3}{4}: ["Add", 2, ["Divide", 3, 4]]

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: boolean;

When a number is encountered, parse it.

Otherwise, return each token making up the number (minus sign, digits, decimal marker, etc…).

Default: true

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.

Default: true

parseUnknownIdentifier: (symbol: string, parser: Parser): "symbol" | "function" | "unknown";

This handler is invoked when the parser encounter a set of tokens at a position that could be a symbol or function.

The symbol argument is one or more tokens.

The handler can return:

  • symbol to indicate the string represent a constant or variable.

  • function to indicate the string is a function name. If an apply function operator (typically, parentheses) follow, parse them as arguments to the function.

  • error, an error condition is raised.

PatternMatchOptions

exact: boolean;
numericTolerance: number;
recursive: boolean;
substitution: BoxedSubstitution;

PostfixEntry

PostfixParseHandler

(parser: Parser, lhs: Expression): Expression | null

PrefixEntry

  • BaseEntry &
  • kind: "prefix";

    Prefix position, with an operand after: ⊛ a

    Example: -, \not.

    parse: PrefixParseHandler;
    precedence: number;

PrefixParseHandler

(parser: Parser, until: Terminator): Expression | null

Rational

  • | [number, number]
  • | [bigint, bigint]

ReplaceOptions

iterationLimit: number;

If iterationLimit > 1, the rules will be repeatedly applied until no rules apply, up to maxIterations 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. If false, only consider the top-level expression.

Default: true

Rule

A rule describes how to modify an expressions that matches a lhs pattern into a new expressions matching rhs.

x-1 ( \to ) 1-x (x+1)(x-1) ( \to ) `x^2-1

The lhs can be expressed as a LaTeX string or a MathJSON expression.

Unbound variables (x, but not Pi) are matched structurally with a a target expression, then the expression is rewritten as the rhs, with the corresponding unbound variables in the rhs replaced by their values in the `lhs.

Pattern symbols (e.g. _1, _a) can be used as well.

In addition:

  • __1 (__a, etc…) match a sequence of one or more expressions
  • ___1 (___a, etc…) match a sequence of zero or more expressions

[lhs: LatexString | SemiBoxedExpression | Pattern, rhs: LatexString | SemiBoxedExpression, options: {condition: LatexString | (wildcards: BoxedSubstitution): boolean; priority: number}]

RuntimeIdentifierTable

The entries of a RuntimeIdentifierTable 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 RuntimeIdentifierTable are created as needed.


RuntimeScope

  • Scope &
  • assumptions: undefined | ExpressionMapInterface<boolean>;
    idTable: RuntimeIdentifierTable;
    lowWaterMark: number;

    Free memory should not go below this level for execution to proceed

    origin: {column: number; line: number; name: string};

    The location of the call site that created this scope

    parentScope: RuntimeScope;

Scope

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 for this scope is exceeded. Default: no limits.

memoryLimit: number;
experimental

Signal out-of-memory when the memory usage for this scope is exceeded. Memory 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

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

(serializer: Serializer, expr: Expression): string

SerializeLatexOptions

invisibleMultiply: LatexString;

LaTeX string used to render an invisible multiply, e.g. in ‘2x’. Leave it empty to join the adjacent terms, or 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, 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}, or use + to insert a + 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): "paren" | "leftright" | "big" | "none";
fractionStyle: (expr: Expression, level: number): "quotient" | "inline-solidus" | "nice-solidus" | "reciprocal" | "factor";
groupStyle: (expr: Expression, level: number): "paren" | "leftright" | "big" | "none";
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

Options for BoxedExpression.simplify()


Substitution

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.


<T> =
[symbol: string]: T}

SymbolAttributes

constant: boolean;

If true the value of the symbol is constant. The value or domain of symbols with this attribute set to true 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 has holdUntil: 'never'
  • GoldenRatio has holdUntil: 'simplify' (symbolic constant)
  • x has holdUntil: 'evaluate' (variables)
  • Pi has holdUntil: 'N' (special numeric constant)

Default: simplify

SymbolDefinition

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 = TranscendentalNumber)


SymbolEntry

  • BaseEntry &
  • kind: "symbol";
    parse: Expression | SymbolParseHandler;
    precedence: number;

    Used for appropriate wrapping (i.e. when to surround it with parens)

SymbolFlags

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;

SymbolParseHandler

(parser: Parser): Expression | null

Terminator

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 function is provided, the function returns true;

minPrec: number;
condition?: (parser: Parser): boolean;
Documentation built with grok