@cortex-js/compute-engine 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/dist/compute-engine.esm.js +27153 -25341
  2. package/dist/compute-engine.js +27124 -25300
  3. package/dist/compute-engine.min.esm.js +88 -23
  4. package/dist/compute-engine.min.js +88 -23
  5. package/dist/math-json.esm.js +42 -196
  6. package/dist/math-json.js +42 -196
  7. package/dist/math-json.min.esm.js +42 -196
  8. package/dist/math-json.min.js +2 -2
  9. package/dist/types/common/ansi-codes.d.ts +30 -4
  10. package/dist/types/common/buffer.d.ts +9 -0
  11. package/dist/types/common/grapheme-splitter.d.ts +1 -1
  12. package/dist/types/common/one-of.d.ts +9 -0
  13. package/dist/types/common/signals.d.ts +1 -1
  14. package/dist/types/common/styled-text.d.ts +28 -0
  15. package/dist/types/common/suggest.d.ts +1 -0
  16. package/dist/types/common/syntax-highlighter.d.ts +40 -0
  17. package/dist/types/common/terminal.d.ts +19 -0
  18. package/dist/types/common/type/parse.d.ts +4 -0
  19. package/dist/types/common/type/primitive.d.ts +8 -0
  20. package/dist/types/common/type/serialize.d.ts +2 -0
  21. package/dist/types/common/type/subtype.d.ts +6 -0
  22. package/dist/types/common/type/types.d.ts +249 -0
  23. package/dist/types/common/type/utils.d.ts +39 -0
  24. package/dist/types/common/utils.d.ts +2 -1
  25. package/dist/types/compute-engine/assume.d.ts +13 -13
  26. package/dist/types/compute-engine/boxed-expression/abstract-boxed-expression.d.ts +71 -47
  27. package/dist/types/compute-engine/boxed-expression/apply.d.ts +5 -0
  28. package/dist/types/compute-engine/boxed-expression/arithmetic-add.d.ts +15 -0
  29. package/dist/types/compute-engine/boxed-expression/arithmetic-divide.d.ts +12 -0
  30. package/dist/types/compute-engine/boxed-expression/arithmetic-multiply.d.ts +16 -0
  31. package/dist/types/compute-engine/boxed-expression/arithmetic-power.d.ts +20 -0
  32. package/dist/types/compute-engine/boxed-expression/ascii-math.d.ts +11 -0
  33. package/dist/types/compute-engine/boxed-expression/box.d.ts +13 -71
  34. package/dist/types/compute-engine/boxed-expression/boxed-function-definition.d.ts +31 -13
  35. package/dist/types/compute-engine/boxed-expression/boxed-function.d.ts +66 -45
  36. package/dist/types/compute-engine/boxed-expression/boxed-number.d.ts +41 -37
  37. package/dist/types/compute-engine/boxed-expression/boxed-patterns.d.ts +2 -2
  38. package/dist/types/compute-engine/boxed-expression/boxed-string.d.ts +13 -9
  39. package/dist/types/compute-engine/boxed-expression/boxed-symbol-definition.d.ts +34 -66
  40. package/dist/types/compute-engine/boxed-expression/boxed-symbol.d.ts +63 -41
  41. package/dist/types/compute-engine/boxed-expression/boxed-tensor.d.ts +44 -27
  42. package/dist/types/compute-engine/boxed-expression/cache.d.ts +6 -0
  43. package/dist/types/compute-engine/boxed-expression/canonical.d.ts +1 -1
  44. package/dist/types/compute-engine/boxed-expression/compare.d.ts +13 -0
  45. package/dist/types/compute-engine/boxed-expression/expand.d.ts +20 -0
  46. package/dist/types/compute-engine/boxed-expression/expression-map.d.ts +1 -1
  47. package/dist/types/compute-engine/boxed-expression/factor.d.ts +7 -6
  48. package/dist/types/compute-engine/boxed-expression/flatten.d.ts +25 -0
  49. package/dist/types/compute-engine/boxed-expression/hold.d.ts +9 -0
  50. package/dist/types/compute-engine/boxed-expression/match.d.ts +2 -4
  51. package/dist/types/compute-engine/boxed-expression/negate.d.ts +10 -0
  52. package/dist/types/compute-engine/boxed-expression/numerics.d.ts +5 -39
  53. package/dist/types/compute-engine/boxed-expression/order.d.ts +26 -14
  54. package/dist/types/compute-engine/{symbolic → boxed-expression}/polynomials.d.ts +11 -15
  55. package/dist/types/compute-engine/{symbolic → boxed-expression}/product.d.ts +18 -24
  56. package/dist/types/compute-engine/boxed-expression/public.d.ts +947 -656
  57. package/dist/types/compute-engine/boxed-expression/rules.d.ts +129 -0
  58. package/dist/types/compute-engine/boxed-expression/serialize.d.ts +2 -2
  59. package/dist/types/compute-engine/boxed-expression/sgn.d.ts +6 -0
  60. package/dist/types/compute-engine/boxed-expression/simplify.d.ts +6 -0
  61. package/dist/types/compute-engine/{solve.d.ts → boxed-expression/solve.d.ts} +5 -5
  62. package/dist/types/compute-engine/{symbolic → boxed-expression}/tensor-fields.d.ts +3 -3
  63. package/dist/types/compute-engine/boxed-expression/terms.d.ts +10 -0
  64. package/dist/types/compute-engine/boxed-expression/trigonometry.d.ts +10 -0
  65. package/dist/types/compute-engine/boxed-expression/utils.d.ts +22 -16
  66. package/dist/types/compute-engine/boxed-expression/validate.d.ts +10 -7
  67. package/dist/types/compute-engine/collection-utils.d.ts +24 -2
  68. package/dist/types/compute-engine/compile.d.ts +3 -3
  69. package/dist/types/compute-engine/compute-engine.d.ts +133 -165
  70. package/dist/types/compute-engine/cost-function.d.ts +11 -1
  71. package/dist/types/compute-engine/function-utils.d.ts +5 -5
  72. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-algebra.d.ts +1 -1
  73. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-arithmetic.d.ts +1 -1
  74. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-calculus.d.ts +1 -1
  75. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-complex.d.ts +1 -1
  76. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-core.d.ts +1 -1
  77. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-linear-algebra.d.ts +1 -1
  78. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-logic.d.ts +1 -1
  79. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-other.d.ts +1 -1
  80. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-relational-operators.d.ts +1 -1
  81. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-sets.d.ts +1 -1
  82. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-statistics.d.ts +1 -1
  83. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-symbols.d.ts +1 -1
  84. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-trigonometry.d.ts +1 -1
  85. package/dist/types/compute-engine/latex-syntax/dictionary/definitions.d.ts +1 -1
  86. package/dist/types/compute-engine/latex-syntax/parse-identifier.d.ts +2 -2
  87. package/dist/types/compute-engine/latex-syntax/parse.d.ts +25 -30
  88. package/dist/types/compute-engine/latex-syntax/public.d.ts +22 -18
  89. package/dist/types/compute-engine/latex-syntax/serialize-number.d.ts +2 -2
  90. package/dist/types/compute-engine/latex-syntax/serializer-style.d.ts +1 -1
  91. package/dist/types/compute-engine/latex-syntax/serializer.d.ts +5 -8
  92. package/dist/types/compute-engine/latex-syntax/tokenizer.d.ts +1 -1
  93. package/dist/types/compute-engine/library/arithmetic.d.ts +4 -2
  94. package/dist/types/compute-engine/library/calculus.d.ts +1 -1
  95. package/dist/types/compute-engine/library/collections.d.ts +24 -1
  96. package/dist/types/compute-engine/library/complex.d.ts +1 -1
  97. package/dist/types/compute-engine/library/control-structures.d.ts +1 -1
  98. package/dist/types/compute-engine/library/core.d.ts +1 -3
  99. package/dist/types/compute-engine/library/invisible-operator.d.ts +4 -0
  100. package/dist/types/compute-engine/library/library.d.ts +2 -4
  101. package/dist/types/compute-engine/library/linear-algebra.d.ts +1 -1
  102. package/dist/types/compute-engine/library/logic.d.ts +5 -1
  103. package/dist/types/compute-engine/library/polynomials.d.ts +1 -1
  104. package/dist/types/compute-engine/library/random-expression.d.ts +1 -1
  105. package/dist/types/compute-engine/library/relational-operator.d.ts +1 -1
  106. package/dist/types/compute-engine/library/sets.d.ts +1 -1
  107. package/dist/types/compute-engine/library/statistics.d.ts +1 -1
  108. package/dist/types/compute-engine/library/trigonometry.d.ts +1 -1
  109. package/dist/types/compute-engine/library/utils.d.ts +46 -40
  110. package/dist/types/compute-engine/numeric-value/big-numeric-value.d.ts +59 -0
  111. package/dist/types/compute-engine/numeric-value/exact-numeric-value.d.ts +77 -0
  112. package/dist/types/compute-engine/numeric-value/machine-numeric-value.d.ts +58 -0
  113. package/dist/types/compute-engine/numeric-value/public.d.ts +110 -0
  114. package/dist/types/compute-engine/numerics/bigint.d.ts +2 -0
  115. package/dist/types/compute-engine/numerics/bignum.d.ts +12 -0
  116. package/dist/types/compute-engine/numerics/expression.d.ts +4 -0
  117. package/dist/types/compute-engine/numerics/interval.d.ts +12 -0
  118. package/dist/types/compute-engine/numerics/monte-carlo.d.ts +19 -0
  119. package/dist/types/compute-engine/numerics/numeric-bigint.d.ts +4 -14
  120. package/dist/types/compute-engine/numerics/numeric-bignum.d.ts +6 -9
  121. package/dist/types/compute-engine/numerics/numeric-complex.d.ts +1 -1
  122. package/dist/types/compute-engine/numerics/numeric.d.ts +9 -59
  123. package/dist/types/compute-engine/numerics/primes.d.ts +3 -3
  124. package/dist/types/compute-engine/numerics/rationals.d.ts +29 -13
  125. package/dist/types/compute-engine/numerics/richardson.d.ts +1 -1
  126. package/dist/types/compute-engine/numerics/special-functions.d.ts +28 -0
  127. package/dist/types/compute-engine/numerics/strings.d.ts +2 -0
  128. package/dist/types/compute-engine/public.d.ts +8 -4
  129. package/dist/types/compute-engine/symbolic/derivative.d.ts +2 -2
  130. package/dist/types/compute-engine/symbolic/distribute.d.ts +5 -0
  131. package/dist/types/compute-engine/{simplify-rules.d.ts → symbolic/simplify-rules.d.ts} +1 -1
  132. package/dist/types/compute-engine/{symbolic → tensor}/tensors.d.ts +3 -3
  133. package/dist/types/compute-engine.d.ts +4 -2
  134. package/dist/types/math-json/identifiers.d.ts +11 -0
  135. package/dist/types/math-json/{math-json-format.d.ts → types.d.ts} +4 -9
  136. package/dist/types/math-json/utils.d.ts +15 -23
  137. package/dist/types/math-json.d.ts +3 -3
  138. package/package.json +11 -11
  139. package/dist/types/compute-engine/boxed-expression/boxed-dictionary.d.ts +0 -48
  140. package/dist/types/compute-engine/boxed-expression/boxed-domain.d.ts +0 -40
  141. package/dist/types/compute-engine/domain-utils.d.ts +0 -19
  142. package/dist/types/compute-engine/library/arithmetic-add.d.ts +0 -21
  143. package/dist/types/compute-engine/library/arithmetic-divide.d.ts +0 -17
  144. package/dist/types/compute-engine/library/arithmetic-multiply.d.ts +0 -16
  145. package/dist/types/compute-engine/library/arithmetic-power.d.ts +0 -11
  146. package/dist/types/compute-engine/library/domains.d.ts +0 -16
  147. package/dist/types/compute-engine/numerics/terms.d.ts +0 -17
  148. package/dist/types/compute-engine/rules.d.ts +0 -20
  149. package/dist/types/compute-engine/symbolic/expand.d.ts +0 -23
  150. package/dist/types/compute-engine/symbolic/flatten.d.ts +0 -9
  151. package/dist/types/compute-engine/symbolic/negate.d.ts +0 -11
  152. package/dist/types/compute-engine/symbolic/utils.d.ts +0 -22
@@ -1,10 +1,141 @@
1
- /* 0.25.0 */
2
- import Decimal from 'decimal.js';
3
- import { Expression, MathJsonNumber, MathJsonString, MathJsonSymbol, MathJsonFunction, MathJsonDictionary, MathJsonIdentifier } from '../../math-json';
1
+ /* 0.26.0 */
2
+ import type { Expression, MathJsonNumber, MathJsonString, MathJsonSymbol, MathJsonFunction, MathJsonIdentifier } from '../../math-json';
4
3
  import type { SerializeLatexOptions, LatexDictionaryEntry, ParseLatexOptions } from '../latex-syntax/public';
5
- import { IndexedLatexDictionary } from '../latex-syntax/dictionary/definitions';
4
+ import type { IndexedLatexDictionary } from '../latex-syntax/dictionary/definitions';
6
5
  import { Rational } from '../numerics/rationals';
7
- import './serialize';
6
+ import { ExactNumericValueData, NumericValue, NumericValueData } from '../numeric-value/public';
7
+ import { BigNum, IBigNum } from '../numerics/bignum';
8
+ import { Type, TypeString } from '../../common/type/types';
9
+ import { AbstractTensor } from '../tensor/tensors';
10
+ import { OneOf } from '../../common/one-of';
11
+ /**
12
+ * :::info[THEORY OF OPERATIONS]
13
+ *
14
+ * To create a boxed expression:
15
+ *
16
+ * ### `ce.box()` and `ce.parse()`
17
+ *
18
+ * Use `ce.box()` or `ce.parse()` to get a canonical expression.
19
+ * - the arguments are put in canonical form
20
+ * - invisible operators are made explicit
21
+ * - a limited number of core simplifications are applied,
22
+ * for example 0 is removed from additions
23
+ * - sequences are flattened: `["Add", 1, ["Sequence", 2, 3]]` is
24
+ * transformed to `["Add", 1, 2, 3]`
25
+ * - associative functions are flattened: `["Add", 1, ["Add", 2, 3]]` is
26
+ * transformed to `["Add", 1, 2, 3]`
27
+ * - the arguments of commutative functions are sorted
28
+ * - identifiers are **not** replaced with their values
29
+ *
30
+ * ### Algebraic methods (expr.add(), expr.mul(), etc...)
31
+ *
32
+ * The boxed expression have some algebraic methods,
33
+ * i.e. `add`, `mul`, `div`, `pow`, etc. These methods are suitable for
34
+ * internal calculations, although they may be used as part of the public
35
+ * API as well.
36
+ *
37
+ * - the operation is performed on the canonical version of the expression
38
+ *
39
+ * - the arguments are not evaluated
40
+ *
41
+ * - the canonical handler (of the corresponding operation) is not called
42
+ *
43
+ * - some additional simplifications over canonicalization are applied.
44
+ * For example number literals are combined.
45
+ * However, the result is exact, and no approximation is made. Use `.N()`
46
+ * to get an approximate value.
47
+ * This is equivalent to calling `simplify()` on the expression (but
48
+ * without simplifying the arguments).
49
+ *
50
+ * - sequences were already flattened as part of the canonicalization process
51
+ *
52
+ * For 'add' and 'mul', which take multiple arguments, separate functions
53
+ * are provided that take an array of arguments. They are equivalent
54
+ * to calling the boxed algebraic method, i.e. `ce.Zero.add(1, 2, 3)` and
55
+ * `add(1, 2, 3)` are equivalent.
56
+ *
57
+ * These methods are not equivalent to calling `expr.evaluate()` on the
58
+ * expression: evaluate will replace identifiers with their values, and
59
+ * evaluate the expression
60
+ *
61
+ * ### `ce._fn()`
62
+ *
63
+ * Use `ce._fn()` to create a new function expression.
64
+ *
65
+ * This is a low level method which is typically invoked in the canonical
66
+ * handler of a function definition.
67
+ *
68
+ * The arguments are not modified. The expression is not put in canonical
69
+ * form. The canonical handler is *not* called.
70
+ *
71
+ * A canonical flag can be set when calling the function, but it only
72
+ * asserts that the function and its arguments are canonical. The caller
73
+ * is responsible for ensuring that is the case.
74
+ *
75
+ *
76
+ * ### `ce.function()`
77
+ *
78
+ * This is a specialized version of `ce.box()`. It is used to create a new
79
+ * function expression.
80
+ *
81
+ * The arguments are put in canonical form and the canonical handler is called.
82
+ *
83
+ * For algebraic functions (add, mul, etc..), use the corresponding
84
+ * canonicalization function, i.e. `canonicalAdd(a, b)` instead of
85
+ * `ce.function('Add', a, b)`.
86
+ *
87
+ * Another option is to use the algebraic methods directly, i.e. `a.add(b)`
88
+ * instead of `ce.function('Add', a, b)`. However, the algebraic methods will
89
+ * apply further simplifications which may or may not be desirable. For
90
+ * example, number literals will be combined.
91
+ *
92
+ * ### Canonical Handlers
93
+ *
94
+ * Canonical handlers are responsible for:
95
+ * - validating the signature (type and number of arguments)
96
+ * - flattening sequences
97
+ * - flattening associative functions
98
+ * - sort the arguments (if the function is commutative)
99
+ * - calling `ce._fn()` to create a new function expression
100
+ * - if the function definition has a hold, they should also put
101
+ * their arguments in canonical form, if appropriate
102
+ *
103
+ * When the canonical handler is invoked, the arguments have been put in
104
+ * canonical form according to the `hold` flag.
105
+ *
106
+ * Some canonical handlers are available as separate functions and can be
107
+ * used directly, for example `canonicalAdd(a, b)` instead of
108
+ * `ce.function('Add', [a, b])`.
109
+ *
110
+ * :::
111
+ */
112
+ export type Sign =
113
+ /** The expression is equal to 0 */
114
+ 'zero'
115
+ /** The expression is > 0 */
116
+ | 'positive'
117
+ /** The expression is < 0 */
118
+ | 'negative'
119
+ /** The expression is >= 0 and isPositive is either false or undefined*/
120
+ | 'non-negative'
121
+ /** The expression is <= 0 and isNegative is either false or undefined*/
122
+ | 'non-positive'
123
+ /** The expression is not equal to 0 (possibly with an imaginary part) and isPositive, isNegative, isUnsigned are all false or undefined */
124
+ | 'not-zero'
125
+ /** The expression has no imaginary part and a non-zero real part and isPositive and isNegative are false or undefined*/
126
+ | 'real-not-zero'
127
+ /** The expression has no imaginary part and isNotZero,isPositive,isNegative,isNonNegative,isNonPositive,isZero are either false or undefined*/
128
+ | 'real'
129
+ /** The expression is NaN */
130
+ | 'nan'
131
+ /** The expression is +∞ */
132
+ | 'positive-infinity'
133
+ /** The expression is -∞ */
134
+ | 'negative-infinity'
135
+ /** The expression is ~∞ */
136
+ | 'complex-infinity'
137
+ /** The expression has an imaginary part or is NaN */
138
+ | 'unsigned';
8
139
  /**
9
140
  * :::info[THEORY OF OPERATIONS]
10
141
  *
@@ -19,7 +150,8 @@ import './serialize';
19
150
  * having to check what kind of instance they are before manipulating them.
20
151
  * :::
21
152
  *
22
- * To get a boxed expression, use `ce.box()` or `ce.parse()`.
153
+ * To get a boxed expression from a LaTeX string use `ce.parse()`, or to
154
+ * get a boxed expression from a MathJSON expression use `ce.box()`.
23
155
  *
24
156
  * @category Boxed Expression
25
157
  *
@@ -42,11 +174,12 @@ export interface BoxedExpression {
42
174
  *
43
175
  * @category Primitive Methods
44
176
  */
45
- valueOf(): number | Object | string | boolean;
177
+ valueOf(): number | any | string | boolean;
46
178
  /** From `Object.toString()`, return a string representation of the
47
179
  * expression. This string is suitable to be output to the console
48
- * for debugging, for example. To get a LaTeX representation of the
49
- * expression, use `expr.latex`.
180
+ * for debugging, for example. It is formatted as a ASCIIMath expression.
181
+ *
182
+ * To get a LaTeX representation of the expression, use `expr.latex`.
50
183
  *
51
184
  * Used when coercing a `BoxedExpression` to a `String`.
52
185
  *
@@ -60,6 +193,7 @@ export interface BoxedExpression {
60
193
  */
61
194
  print(): void;
62
195
  /** Similar to`expr.valueOf()` but includes a hint.
196
+ *
63
197
  * @category Primitive Methods
64
198
  */
65
199
  [Symbol.toPrimitive](hint: 'number' | 'string' | 'default'): number | string | null;
@@ -77,12 +211,15 @@ export interface BoxedExpression {
77
211
  * Will ignore any LaTeX metadata.
78
212
  */
79
213
  toLatex(options?: Partial<SerializeLatexOptions>): LatexString;
214
+ verbatimLatex?: string;
80
215
  /** If `true`, this expression is in a canonical form. */
81
216
  get isCanonical(): boolean;
82
217
  /** For internal use only, set when a canonical expression is created.
83
218
  * @internal
84
219
  */
85
220
  set isCanonical(val: boolean);
221
+ /** If `true`, this expression is in a structural form. */
222
+ get isStructural(): boolean;
86
223
  /** MathJSON representation of this expression.
87
224
  *
88
225
  * This representation always use shorthands when possible. Metadata is not
@@ -93,7 +230,7 @@ export interface BoxedExpression {
93
230
  * The expression is represented exactly and no sugaring is applied. For
94
231
  * example, `["Power", "x", 2]` is not represented as `["Square", "x"]`.
95
232
  *
96
- * For more control over the serialization, use `ce.serialize()`.
233
+ * For more control over the serialization, use `expr.toMathJson()`.
97
234
  *
98
235
  * :::info[Note]
99
236
  * Applicable to canonical and non-canonical expressions.
@@ -103,15 +240,19 @@ export interface BoxedExpression {
103
240
  readonly json: Expression;
104
241
  /**
105
242
  * The scope in which this expression has been defined.
106
- * Is null when the expression is not canonical.
243
+ *
244
+ * Is `null` when the expression is not canonical.
107
245
  */
108
246
  readonly scope: RuntimeScope | null;
109
- /** From `Object.is()`. Equivalent to `BoxedExpression.isSame()`
247
+ /**
248
+ * Equivalent to `BoxedExpression.isSame()` but the argument can be
249
+ * a JavaScript primitive. For example, `expr.is(2)` is equivalent to
250
+ * `expr.isSame(ce.number(2))`.
110
251
  *
111
252
  * @category Primitive Methods
112
253
  *
113
254
  */
114
- is(rhs: unknown): boolean;
255
+ is(rhs: any): boolean;
115
256
  /** @internal */
116
257
  readonly hash: number;
117
258
  /** LaTeX representation of this expression.
@@ -119,7 +260,7 @@ export interface BoxedExpression {
119
260
  * If the expression was parsed from LaTeX, the LaTeX representation is
120
261
  * the same as the input LaTeX.
121
262
  *
122
- * Otherwise, the serialization can be customized with `ComputeEngine.latexOptions`
263
+ * To customize the serialization, use `expr.toLatex()`.
123
264
  *
124
265
  * :::info[Note]
125
266
  * Applicable to canonical and non-canonical expressions.
@@ -141,11 +282,16 @@ export interface BoxedExpression {
141
282
  * :::info[Note]
142
283
  * Applicable to canonical and non-canonical expressions.
143
284
  * :::
144
-
145
- * @category Symbol Expression
285
+ *
286
+ * @category Symbol Expression
146
287
  *
147
288
  */
148
289
  readonly symbol: string | null;
290
+ /**
291
+ * @category Symbol Expression
292
+ *
293
+ */
294
+ readonly tensor: null | AbstractTensor<'expression'>;
149
295
  /** If this expression is a string, return the value of the string.
150
296
  * Otherwise, return `null`.
151
297
  *
@@ -157,14 +303,14 @@ export interface BoxedExpression {
157
303
  *
158
304
  */
159
305
  readonly string: string | null;
160
- /** All the subexpressions matching the head
306
+ /** All the subexpressions matching the named operator, recursively.
161
307
  *
162
308
  * :::info[Note]
163
309
  * Applicable to canonical and non-canonical expressions.
164
310
  * :::
165
311
  *
166
312
  */
167
- getSubexpressions(head: string): ReadonlyArray<BoxedExpression>;
313
+ getSubexpressions(name: string): ReadonlyArray<BoxedExpression>;
168
314
  /** All the subexpressions in this expression, recursively
169
315
  *
170
316
  * :::info[Note]
@@ -195,7 +341,10 @@ export interface BoxedExpression {
195
341
  *
196
342
  */
197
343
  readonly freeVariables: ReadonlyArray<string>;
198
- /** All the `["Error"]` subexpressions
344
+ /** All the `["Error"]` subexpressions.
345
+ *
346
+ * If an expression includes an error, the expression is also an error.
347
+ * In that case, the `this.isValid` property is `false`.
199
348
  *
200
349
  * :::info[Note]
201
350
  * Applicable to canonical and non-canonical expressions.
@@ -203,22 +352,34 @@ export interface BoxedExpression {
203
352
  *
204
353
  */
205
354
  readonly errors: ReadonlyArray<BoxedExpression>;
206
- /** All boxed expressions have a head.
207
- *
208
- * If not a function this can be `Symbol`, `String`, `Number` or `Dictionary`.
209
- *
210
- * If the head expression can be represented as a string, it is returned
211
- * as a string.
355
+ /** `true` if this expression or any of its subexpressions is an `["Error"]`
356
+ * expression.
212
357
  *
213
358
  * :::info[Note]
214
- * Applicable to canonical and non-canonical expressions. The head
215
- * of a non-canonical expression may be different than the head of its
216
- * canonical counterpart. For example the canonical counterpart of `["Divide", 5, 7]` is `["Rational", 5, 7]`.
359
+ * Applicable to canonical and non-canonical expressions. For
360
+ * non-canonical expression, this may indicate a syntax error while parsing
361
+ * LaTeX. For canonical expression, this may indicate argument type
362
+ * mismatch, or missing or unexpected arguments.
217
363
  * :::
218
-
219
- */
220
- readonly head: BoxedExpression | string;
221
- /** The list of arguments of the function, its "tail".
364
+ *
365
+ * @category Symbol Expression
366
+ *
367
+ */
368
+ readonly isValid: boolean;
369
+ /**
370
+ * The name of the operator of the expression.
371
+ *
372
+ * For example, the name of the operator of `["Add", 2, 3]` is `"Add"`.
373
+ *
374
+ * A string literal has a `"String"` operator.
375
+ *
376
+ * A symbol has a `"Symbol"` operator.
377
+ *
378
+ * A number has a `"Number"`, `"Real"`, `"Rational"` or `"Integer"` operator.
379
+ *
380
+ */
381
+ readonly operator: string;
382
+ /** The list of operands of the function.
222
383
  *
223
384
  * If the expression is not a function, return `null`.
224
385
  *
@@ -243,7 +404,9 @@ export interface BoxedExpression {
243
404
  *
244
405
  */
245
406
  readonly nops: number;
246
- /** First operand, i.e.`this.ops[0]`
407
+ /** First operand, i.e.`this.ops[0]`.
408
+ *
409
+ * If there is no first operand, return the symbol `Nothing`.
247
410
  *
248
411
  * :::info[Note]
249
412
  * Applicable to canonical and non-canonical expressions.
@@ -255,6 +418,8 @@ export interface BoxedExpression {
255
418
  */
256
419
  readonly op1: BoxedExpression;
257
420
  /** Second operand, i.e.`this.ops[1]`
421
+ *
422
+ * If there is no second operand, return the symbol `Nothing`.
258
423
  *
259
424
  * :::info[Note]
260
425
  * Applicable to canonical and non-canonical expressions.
@@ -266,6 +431,8 @@ export interface BoxedExpression {
266
431
  */
267
432
  readonly op2: BoxedExpression;
268
433
  /** Third operand, i.e. `this.ops[2]`
434
+ *
435
+ * If there is no third operand, return the symbol `Nothing`.
269
436
  *
270
437
  * :::info[Note]
271
438
  * Applicable to canonical and non-canonical expressions.
@@ -276,37 +443,9 @@ export interface BoxedExpression {
276
443
  *
277
444
  */
278
445
  readonly op3: BoxedExpression;
279
- /** `true` if this expression or any of its subexpressions is an `["Error"]`
280
- * expression.
281
- *
282
- * :::info[Note]
283
- * Applicable to canonical and non-canonical expressions. For
284
- * non-canonical expression, this may indicate a syntax error while parsing
285
- * LaTeX. For canonical expression, this may indicate argument domain
286
- * mismatch, or missing or unexpected arguments.
287
- * :::
288
- *
289
- * @category Symbol Expression
290
- *
291
- */
292
- readonly isValid: boolean;
293
- /**
294
- * An exact value is not further transformed when evaluated. To get an
295
- * approximate evaluation of an exact value, use `.N()`.
296
- *
297
- * Exact numbers are:
298
- * - rationals (including integers)
299
- * - complex numbers with integer real and imaginary parts (Gaussian integers)
300
- * - square root of rationals
301
- *
302
- * Non-exact values includes:
303
- * - numbers with a fractional part
304
- * - complex numbers with a real or imaginary fractional part
305
- *
306
- */
307
- readonly isExact: boolean;
308
446
  /** If true, the value of the expression never changes and evaluating it has
309
447
  * no side-effects.
448
+ *
310
449
  * If false, the value of the expression may change, if the
311
450
  * value of other expression changes or for other reasons.
312
451
  *
@@ -320,7 +459,17 @@ export interface BoxedExpression {
320
459
  * :::
321
460
  */
322
461
  readonly isPure: boolean;
323
- /** True if the expression is a constant, that is a symbol with an immutable value */
462
+ /**
463
+ * True if the the value of the expression does not depend on the value of
464
+ * any other expression.
465
+ *
466
+ * For example, a number literal, a symbol with a constant value.
467
+ * - `2` is constant
468
+ * - `Pi` is constant
469
+ * - `["Add", "Pi", 2]` is constant
470
+ * - `x` is not constant
471
+ * - `["Add", "x", 2]` is not constant
472
+ */
324
473
  readonly isConstant: boolean;
325
474
  /**
326
475
  * Return the canonical form of this expression.
@@ -340,11 +489,31 @@ export interface BoxedExpression {
340
489
  *
341
490
  */
342
491
  get canonical(): BoxedExpression;
492
+ /**
493
+ * Return the structural form of this expression.
494
+ *
495
+ * Some expressions, such as rational numbers, are represented with
496
+ * a `BoxedExpression` object. In some cases, for example when doing a
497
+ * structural comparison of two expressions, it is useful to have a
498
+ * structural representation of the expression where the rational numbers
499
+ * is represented by a function expression instead.
500
+ *
501
+ * If there is a structural representation of the expression, return it,
502
+ * otherwise return `this`.
503
+ *
504
+ */
505
+ get structural(): BoxedExpression;
343
506
  /**
344
507
  * Replace all the symbols in the expression as indicated.
345
508
  *
346
509
  * Note the same effect can be achieved with `this.replace()`, but
347
- * using `this.subs()` is more efficient, and simpler.
510
+ * using `this.subs()` is more efficient, and simpler, but limited
511
+ * to replacing symbols.
512
+ *
513
+ * The result is bound to the current scope, not to `this.scope`.
514
+ *
515
+ * If `options.canonical` is not set, the result is canonical if `this`
516
+ * is canonical.
348
517
  *
349
518
  * :::info[Note]
350
519
  * Applicable to canonical and non-canonical expressions.
@@ -355,35 +524,42 @@ export interface BoxedExpression {
355
524
  canonical?: CanonicalOptions;
356
525
  }): BoxedExpression;
357
526
  /**
358
- * Recursively replace all the terms in the expression as indicated.
527
+ * Recursively replace all the subexpressions in the expression as indicated.
359
528
  *
360
- * To remove a subexpression, return an empty Sequence expression.
529
+ * To remove a subexpression, return an empty `["Sequence"]` expression.
361
530
  *
362
531
  * The canonical option is applied to each function subexpression after
363
532
  * the substitution is applied.
533
+ *
534
+ * If no `options.canonical` is set, the result is canonical if `this`
535
+ * is canonical.
536
+ *
537
+ * **Default**: `{ canonical: this.isCanonical, recursive: true }`
364
538
  */
365
539
  map(fn: (expr: BoxedExpression) => BoxedExpression, options?: {
366
540
  canonical: CanonicalOptions;
541
+ recursive?: boolean;
367
542
  }): BoxedExpression;
368
543
  /**
369
- * Transform the expression by applying the rules:
544
+ * Transform the expression by applying one or more replacement rules:
370
545
  *
371
- * If the expression matches the `match` pattern, replace it with
372
- * the `replace` pattern.
546
+ * - If the expression matches the `match` pattern and the `condition`
547
+ * predicate is true, replace it with the `replace` pattern.
373
548
  *
374
- * If no rules apply, return `null`.
549
+ * - If no rules apply, return `null`.
375
550
  *
376
- * See also `subs` for a simple substitution.
551
+ * See also `expr.subs()` for a simple substitution of symbols.
377
552
  *
553
+ * If `options.canonical` is not set, the result is canonical if `this`
554
+ * is canonical.
378
555
  *
379
556
  * :::info[Note]
380
- * Applicable to canonical and non-canonical expressions. If the
381
- * expression is non-canonical, the result is also non-canonical.
557
+ * Applicable to canonical and non-canonical expressions.
382
558
  * :::
383
559
  */
384
- replace(rules: BoxedRuleSet | Rule | Rule[], options?: ReplaceOptions): null | BoxedExpression;
560
+ replace(rules: BoxedRuleSet | Rule | Rule[], options?: Partial<ReplaceOptions>): null | BoxedExpression;
385
561
  /**
386
- * True if the expression includes a symbol `v` or a function head `v`.
562
+ * True if the expression includes a symbol `v` or a function operator `v`.
387
563
  *
388
564
  * :::info[Note]
389
565
  * Applicable to canonical and non-canonical expressions.
@@ -392,7 +568,9 @@ export interface BoxedExpression {
392
568
  has(v: string | string[]): boolean;
393
569
  /** Structural/symbolic equality (weak equality).
394
570
  *
395
- * `ce.parse('1+x').isSame(ce.parse('x+1'))` is `false`
571
+ * `ce.parse('1+x').isSame(ce.parse('x+1'))` is `false`.
572
+ *
573
+ * See `expr.isEqual()` for mathematical equality.
396
574
  *
397
575
  * :::info[Note]
398
576
  * Applicable to canonical and non-canonical expressions.
@@ -401,6 +579,12 @@ export interface BoxedExpression {
401
579
  * @category Relational Operator
402
580
  */
403
581
  isSame(rhs: BoxedExpression): boolean;
582
+ /**
583
+ * Return this expression expressed as a numerator and denominator.
584
+ */
585
+ get numerator(): BoxedExpression;
586
+ get denominator(): BoxedExpression;
587
+ get numeratorDenominator(): [BoxedExpression, BoxedExpression];
404
588
  /**
405
589
  * If this expression matches `pattern`, return a substitution that makes
406
590
  * `pattern` equal to `this`. Otherwise return `null`.
@@ -419,7 +603,7 @@ export interface BoxedExpression {
419
603
  * :::
420
604
  *
421
605
  */
422
- match(pattern: Decimal | Complex | [num: number, denom: number] | SemiBoxedExpression | BoxedExpression, options?: PatternMatchOptions): BoxedSubstitution | null;
606
+ match(pattern: BoxedExpression, options?: PatternMatchOptions): BoxedSubstitution | null;
423
607
  /**
424
608
  * "Not a Number".
425
609
  *
@@ -434,119 +618,199 @@ export interface BoxedExpression {
434
618
  */
435
619
  readonly isNaN: boolean | undefined;
436
620
  /**
437
- * The numeric value of this expression is 0.
621
+ * The numeric value of this expression is `±Infinity` or Complex Infinity
438
622
  *
439
623
  * @category Numeric Expression
440
624
  */
441
- readonly isZero: boolean | undefined;
442
- /**
443
- * The numeric value of this expression is not 0.
625
+ readonly isInfinity: boolean | undefined;
626
+ /** This expression is a number, but not `±Infinity`, 'ComplexInfinity` or
627
+ * `NaN`
628
+ *
444
629
  * @category Numeric Expression
445
630
  */
446
- readonly isNotZero: boolean | undefined;
631
+ readonly isFinite: boolean | undefined;
447
632
  /**
448
- * The numeric value of this expression is not 1.
449
633
  * @category Numeric Expression
450
634
  */
451
- readonly isOne: boolean | undefined;
635
+ readonly isEven: boolean | undefined;
452
636
  /**
453
- * The numeric value of this expression is not -1.
454
637
  * @category Numeric Expression
455
638
  */
456
- readonly isNegativeOne: boolean | undefined;
457
- /** The numeric value of this expression is ±Infinity or Complex Infinity
639
+ readonly isOdd: boolean | undefined;
640
+ /**
641
+ * Return the value of this expression, if a number literal.
642
+ *
643
+ * Note it is possible for `this.numericValue` to be `null`, and for
644
+ * `this.isNotZero` to be true. For example, when a symbol has been
645
+ * defined with an assumption.
646
+ *
647
+ * Conversely, `this.isNumber` may be true even if `numericValue` is `null`,
648
+ * example the symbol `Pi` return `true` for `isNumber` but `numericValue` is
649
+ * `null`. Its value can be accessed with `.N().numericValue`.
650
+ *
651
+ * To check if an expression is a number literal, use `this.isNumberLiteral`.
652
+ * If `this.isNumberLiteral` is `true`, `this.numericValue` is not `null`
458
653
  *
459
654
  * @category Numeric Expression
655
+ *
460
656
  */
461
- readonly isInfinity: boolean | undefined;
462
- /** This expression is a number, but not ±Infinity and not `NaN`
657
+ readonly numericValue: number | NumericValue | null;
658
+ /**
659
+ * Return `true` if this expression is a number literal, for example
660
+ * `2`, `3.14`, `1/2`, `√2` etc.
661
+ *
662
+ * This is equivalent to checking if `this.numericValue` is not `null`.
463
663
  *
464
664
  * @category Numeric Expression
665
+ *
465
666
  */
466
- readonly isFinite: boolean | undefined;
667
+ readonly isNumberLiteral: boolean;
467
668
  /**
468
- * @category Numeric Expression
669
+ * Return `true` if this expression is a function expression.
670
+ *
671
+ * If `true`, `this.ops` is not `null`, and `this.operator` is the name
672
+ * of the function.
469
673
  */
470
- readonly isEven: boolean | undefined;
674
+ readonly isFunctionExpression: boolean;
471
675
  /**
676
+ * If this expression is a number literal or a symbol with a value that
677
+ * is a number literal, return the real part of the value.
678
+ *
679
+ * If the expression is not a number literal, or a symbol with a value
680
+ * that is a number literal, return `NaN` (not a number).
681
+ *
472
682
  * @category Numeric Expression
473
683
  */
474
- readonly isOdd: boolean | undefined;
684
+ readonly re: number;
475
685
  /**
686
+ * If this expression is a number literal or a symbol with a value that
687
+ * is a number literal, return the imaginary part of the value. If the value
688
+ * is a real number, the imaginary part is 0.
689
+ *
690
+ * If the expression is not a number literal, or a symbol with a value
691
+ * that is a number literal, return `NaN` (not a number).
692
+ *
476
693
  * @category Numeric Expression
477
694
  */
478
- readonly isPrime: boolean | undefined;
695
+ readonly im: number;
479
696
  /**
697
+ * If this expression is a number literal or a symbol with a value that
698
+ * is a number literal, return the real part of the value as a `BigNum`.
699
+ *
700
+ * If the value is not available as a bignum return `undefined`. That is,
701
+ * the value is not upconverted to a bignum.
702
+ *
703
+ * To get the real value either as a bignum or a number, use
704
+ * `this.bignumRe ?? this.re`. When using this pattern, the value is
705
+ * returned as a bignum if available, otherwise as a number or NaN if
706
+ * the value is not a number literal or a symbol with a value that is a
707
+ * number literal.
708
+ *
480
709
  * @category Numeric Expression
710
+ *
481
711
  */
482
- readonly isComposite: boolean | undefined;
712
+ readonly bignumRe: BigNum | undefined;
483
713
  /**
484
- * Return the value of this expression, if a number literal.
714
+ * If this expression is a number literal, return the imaginary part as a
715
+ * `BigNum`.
485
716
  *
486
- * Note it is possible for `numericValue` to be `null`, and for `isNotZero`
487
- * to be true. For example, when a symbol has been defined with an assumption.
717
+ * It may be 0 if the number is real.
488
718
  *
489
- * Conversely, `isNumber` may be true even if `numericValue` is `null`,
490
- * example the symbol `Pi` return true for `isNumber` but `numericValue` is
491
- * `null`. Its value can be accessed with `.value.numericValue`
719
+ * If the expression is not a number literal or the value is not available
720
+ * as a bignum return `undefined`. That is, the value is not upconverted
721
+ * to a bignum.
492
722
  *
493
- * @category Numeric Expression
723
+ * To get the imaginary value either as a bignum or a number, use
724
+ * `this.bignumIm ?? this.im`. When using this pattern, the value is
725
+ * returned as a bignum if available, otherwise as a number or NaN if
726
+ * the value is not a number literal or a symbol with a value that is a
727
+ * number literal.
494
728
  *
729
+ * @category Numeric Expression
495
730
  */
496
- readonly numericValue: number | Decimal | Complex | Rational | null;
497
- /** The shape describes the axis of the expression.
731
+ readonly bignumIm: BigNum | undefined;
732
+ /**
733
+ * Attempt to factor a numeric coefficient `c` and a `rest` out of a
734
+ * canonical expression such that `rest.mul(c)` is equal to `this`.
735
+ *
736
+ * Attempts to make `rest` a positive value (i.e. pulls out negative sign).
737
+ *
738
+ * For example:
739
+ *
740
+ * ['Multiply', 2, 'x', 3, 'a']
741
+ * -> [NumericValue(6), ['Multiply', 'x', 'a']]
742
+ *
743
+ * ['Divide', ['Multiply', 2, 'x'], ['Multiply', 3, 'y', 'a']]
744
+ * -> [NumericValue({rational: [2, 3]}), ['Divide', 'x', ['Multiply, 'y', 'a']]]
745
+ */
746
+ toNumericValue(): [NumericValue, BoxedExpression];
747
+ neg(): BoxedExpression;
748
+ inv(): BoxedExpression;
749
+ abs(): BoxedExpression;
750
+ add(rhs: number | BoxedExpression): BoxedExpression;
751
+ sub(rhs: BoxedExpression): BoxedExpression;
752
+ mul(rhs: NumericValue | number | BoxedExpression): BoxedExpression;
753
+ div(rhs: number | BoxedExpression): BoxedExpression;
754
+ pow(exp: number | BoxedExpression): BoxedExpression;
755
+ root(exp: number | BoxedExpression): BoxedExpression;
756
+ sqrt(): BoxedExpression;
757
+ ln(base?: number | BoxedExpression): BoxedExpression;
758
+ /**
759
+ *
760
+ * The shape describes the axis of the expression.
761
+ *
498
762
  * When the expression is a scalar (number), the shape is `[]`.
499
- * When the expression is a vector, the shape is `[n]`.
500
- * When the expression is a matrix, the shape is `[n, m]`.
763
+ *
764
+ * When the expression is a vector of length `n`, the shape is `[n]`.
765
+ *
766
+ * When the expression is a `n` by `m` matrix, the shape is `[n, m]`.
501
767
  */
502
768
  readonly shape: number[];
503
- /** 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` */
769
+ /** Return 0 for a scalar, 1 for a vector, 2 for a matrix, > 2 for
770
+ * a multidimensional matrix.
771
+ *
772
+ * The rank is equivalent to the length of `expr.shape` */
504
773
  readonly rank: number;
505
774
  /**
506
- * Return the following, depending on the value of this expression:
507
- *
508
- * * `-1` if it is < 0
509
- * * `0` if it is = 0
510
- * * `+1` if it is > 0
511
- * * `undefined` this value may be positive, negative or zero. We don't know
512
- * right now (a symbol with an Integer domain, but no currently assigned
513
- * value, for example)
514
- * * `null` this value will never be positive, negative or zero (`NaN`,
515
- * a string or a complex number for example)
775
+ * Return the sign of the expression.
516
776
  *
517
777
  * Note that complex numbers have no natural ordering,
518
- * so if the value is a complex number, `sgn` is either 0, or `null`
778
+ * so if the value is an imaginary number (a complex number with a non-zero
779
+ * imaginary part), `this.sgn` will return `unsigned`.
519
780
  *
520
781
  * If a symbol, this does take assumptions into account, that is `this.sgn`
521
- * will return `1` if `isPositive` is `true`, even if this expression has
522
- * no value
782
+ * will return `positive` if the symbol is assumed to be positive
783
+ * (using `ce.assume()`).
523
784
  *
524
785
  * @category Numeric Expression
525
786
  *
526
787
  */
527
- readonly sgn: -1 | 0 | 1 | undefined | null;
788
+ readonly sgn: Sign | undefined;
528
789
  /** If the expressions cannot be compared, return `undefined`
529
790
  *
530
791
  * The numeric value of both expressions are compared.
531
792
  *
793
+ * The expressions are evaluated before being compared, which may be
794
+ * expensive.
795
+ *
532
796
  * @category Relational Operator
533
797
  */
534
- isLess(rhs: BoxedExpression): boolean | undefined;
798
+ isLess(other: number | BoxedExpression): boolean | undefined;
535
799
  /**
536
800
  * The numeric value of both expressions are compared.
537
801
  * @category Relational Operator
538
802
  */
539
- isLessEqual(rhs: BoxedExpression): boolean | undefined;
803
+ isLessEqual(other: number | BoxedExpression): boolean | undefined;
540
804
  /**
541
805
  * The numeric value of both expressions are compared.
542
806
  * @category Relational Operator
543
807
  */
544
- isGreater(rhs: BoxedExpression): boolean | undefined;
808
+ isGreater(other: number | BoxedExpression): boolean | undefined;
545
809
  /**
546
810
  * The numeric value of both expressions are compared.
547
811
  * @category Relational Operator
548
812
  */
549
- isGreaterEqual(rhs: BoxedExpression): boolean | undefined;
813
+ isGreaterEqual(other: number | BoxedExpression): boolean | undefined;
550
814
  /** The numeric value of this expression is > 0, same as `isGreater(0)`
551
815
  *
552
816
  * @category Numeric Expression
@@ -567,34 +831,6 @@ export interface BoxedExpression {
567
831
  * @category Numeric Expression
568
832
  */
569
833
  readonly isNonPositive: boolean | undefined;
570
- /** The keys of the dictionary.
571
- *
572
- * If this expression not a dictionary, return `null`
573
- *
574
- * @category Dictionary Expression
575
- *
576
- */
577
- readonly keys: IterableIterator<string> | null;
578
- /**
579
- *
580
- * @category Dictionary Expression
581
- */
582
- readonly keysCount: number;
583
- /**
584
- * If this expression is a dictionary, return the value of the `key` entry.
585
- *
586
- * @category Dictionary Expression
587
- *
588
- */
589
- getKey(key: string): BoxedExpression | undefined;
590
- /**
591
- * If this expression is a dictionary, return true if the
592
- * dictionary has a `key` entry.
593
- *
594
- * @category Dictionary Expression
595
- *
596
- */
597
- hasKey(key: string): boolean;
598
834
  /** Wikidata identifier.
599
835
  *
600
836
  * :::info[Note]
@@ -613,7 +849,7 @@ export interface BoxedExpression {
613
849
  */
614
850
  readonly description: undefined | string[];
615
851
  /** An optional URL pointing to more information about the symbol or
616
- * function head.
852
+ * function operator.
617
853
  *
618
854
  * :::info[Note]
619
855
  * `undefined` if not a canonical expression.
@@ -630,8 +866,8 @@ export interface BoxedExpression {
630
866
  */
631
867
  readonly complexity: number | undefined;
632
868
  /**
633
- * For symbols and functions, a possible definition associated with the
634
- * expression. `baseDefinition` is the base class of symbol and function
869
+ * For symbols and functions, a definition associated with the
870
+ * expression. `this.baseDefinition` is the base class of symbol and function
635
871
  * definition.
636
872
  *
637
873
  * :::info[Note]
@@ -641,7 +877,7 @@ export interface BoxedExpression {
641
877
  */
642
878
  readonly baseDefinition: BoxedBaseDefinition | undefined;
643
879
  /**
644
- * For functions, a possible definition associated with the expression.
880
+ * For functions, a definition associated with the expression.
645
881
  *
646
882
  * :::info[Note]
647
883
  * `undefined` if not a canonical expression or not a function.
@@ -650,7 +886,7 @@ export interface BoxedExpression {
650
886
  */
651
887
  readonly functionDefinition: BoxedFunctionDefinition | undefined;
652
888
  /**
653
- * For symbols, a possible definition associated with the expression.
889
+ * For symbols, a definition associated with the expression.
654
890
  *
655
891
  * Return `undefined` if not a symbol
656
892
  *
@@ -658,17 +894,17 @@ export interface BoxedExpression {
658
894
  readonly symbolDefinition: BoxedSymbolDefinition | undefined;
659
895
  /**
660
896
  *
661
- * Infer the domain of this expression.
897
+ * Infer the type of this expression.
662
898
  *
663
- * If the domain of this expression is already known, return `false`.
899
+ * If the type of this expression is already known, return `false`.
664
900
  *
665
- * If the domain was not set, set it to the inferred domain, return `true`
666
- * If the domain was previously inferred, adjust it by widening it,
901
+ * If the type was not set, set it to the inferred type, return `true`
902
+ * If the type was previously inferred, adjust it by widening it,
667
903
  * return `true`
668
904
  *
669
905
  * @internal
670
906
  */
671
- infer(domain: BoxedDomain): boolean;
907
+ infer(t: Type): boolean;
672
908
  /**
673
909
  * Update the definition associated with this expression, using the
674
910
  * current scope (`ce.context`).
@@ -687,16 +923,13 @@ export interface BoxedExpression {
687
923
  */
688
924
  reset(): void;
689
925
  /**
690
- * Return a simpler form of the canonical form of this expression.
926
+ * Return a simpler form of this expression.
691
927
  *
692
928
  * A series of rewriting rules are applied repeatedly, until no more rules
693
929
  * apply.
694
930
  *
695
- * If a custom `simplify` handler is associated with this function
696
- * definition, it is invoked.
697
- *
698
931
  * The values assigned to symbols and the assumptions about symbols may be
699
- * used, for example `arg.isInteger` or `arg.isPositive`.
932
+ * used, for example `expr.isInteger` or `expr.isPositive`.
700
933
  *
701
934
  * No calculations involving decimal numbers (numbers that are not
702
935
  * integers) are performed but exact calculations may be performed,
@@ -704,10 +937,12 @@ export interface BoxedExpression {
704
937
  *
705
938
  * \\( \sin(\frac{\pi}{4}) \longrightarrow \frac{\sqrt{2}}{2} \\).
706
939
  *
707
- * The result is in canonical form.
940
+ * The result is canonical.
941
+ *
942
+ * To manipulate symbolically non-canonical expressions, use `expr.replace()`.
708
943
  *
709
944
  */
710
- simplify(options?: SimplifyOptions): BoxedExpression;
945
+ simplify(options?: Partial<SimplifyOptions>): BoxedExpression;
711
946
  /**
712
947
  * Return the value of the canonical form of this expression.
713
948
  *
@@ -721,11 +956,11 @@ export interface BoxedExpression {
721
956
  * example modifying the `ComputeEngine` environment, such as its set of
722
957
  * assumptions.
723
958
  *
724
- * Only exact calculations are performed, no approximate calculations on
725
- * decimal numbers (non-integer numbers). Constants, rational numbers and
726
- * square root of rational numbers are preserved.
959
+ * The result may be a rational number or the product of a rational number
960
+ * and the square root of an integer.
727
961
  *
728
- * To perform approximate calculations, use `expr.N()` instead.
962
+ * To perform approximate calculations, use `expr.N()` instead,
963
+ * or set `options.numericApproximation` to `true`.
729
964
  *
730
965
  * The result of `expr.evaluate()` may be the same as `expr.simplify()`.
731
966
  *
@@ -738,8 +973,8 @@ export interface BoxedExpression {
738
973
  * Any necessary calculations, including on decimal numbers (non-integers),
739
974
  * are performed.
740
975
  *
741
- * The calculations are performed according to the `numericMode` and
742
- * `precision` properties of the `ComputeEngine`.
976
+ * The calculations are performed according to the
977
+ * `precision` property of the `ComputeEngine`.
743
978
  *
744
979
  * To only perform exact calculations, use `this.evaluate()` instead.
745
980
  *
@@ -748,10 +983,35 @@ export interface BoxedExpression {
748
983
  *
749
984
  * The result is in canonical form.
750
985
  */
751
- N(options?: NOptions): BoxedExpression;
986
+ N(): BoxedExpression;
987
+ /**
988
+ * Compile the expression to a JavaScript function.
989
+ *
990
+ * The function takes an object as argument, with the keys being the
991
+ * symbols in the expression, and returns the value of the expression.
992
+ *
993
+ *
994
+ * ```javascript
995
+ * const expr = ce.parse('x^2 + y^2');
996
+ * const f = expr.compile('javascript');
997
+ * console.log(f({x: 2, y: 3}));
998
+ * ```
999
+ */
752
1000
  compile(to?: 'javascript', options?: {
753
1001
  optimize: ('simplify' | 'evaluate')[];
754
1002
  }): ((args: Record<string, any>) => any | undefined) | undefined;
1003
+ /**
1004
+ * If this is an equation, solve the equation for the variables in vars.
1005
+ * Otherwise, solve the equation `this = 0` for the variables in vars.
1006
+ *
1007
+ *
1008
+ * ```javascript
1009
+ * const expr = ce.parse('x^2 + 2*x + 1 = 0');
1010
+ * console.log(expr.solve('x'));
1011
+ * ```
1012
+ *
1013
+ *
1014
+ */
755
1015
  solve(vars: Iterable<string> | string | BoxedExpression | Iterable<BoxedExpression>): null | ReadonlyArray<BoxedExpression>;
756
1016
  /**
757
1017
  * Return a JavaScript primitive representing the value of this expression.
@@ -759,7 +1019,7 @@ export interface BoxedExpression {
759
1019
  * Equivalent to `expr.N().valueOf()`.
760
1020
  *
761
1021
  */
762
- get value(): number | boolean | string | Object | undefined;
1022
+ get value(): number | boolean | string | object | undefined;
763
1023
  /**
764
1024
  * Only the value of variables can be changed (symbols that are not
765
1025
  * constants).
@@ -771,7 +1031,7 @@ export interface BoxedExpression {
771
1031
  * :::
772
1032
  *
773
1033
  */
774
- set value(value: boolean | string | Decimal | Complex | {
1034
+ set value(value: boolean | string | BigNum | {
775
1035
  re: number;
776
1036
  im: number;
777
1037
  } | {
@@ -780,44 +1040,47 @@ export interface BoxedExpression {
780
1040
  } | number[] | BoxedExpression | number | undefined);
781
1041
  /**
782
1042
  *
783
- * The domain of the value of this expression.
784
- *
785
- * If a function expression, the domain of the value of the function
786
- * (the codomain of the function).
1043
+ * The type of the value of this expression.
787
1044
  *
788
- * If a symbol the domain of the value of the symbol.
1045
+ * If a function expression, the type of the value of the function
1046
+ * (the result type).
789
1047
  *
790
- * Use `expr.head` to determine if an expression is a symbol or function
791
- * expression.
1048
+ * If a symbol the type of the value of the symbol.
792
1049
  *
793
1050
  * :::info[Note]
794
- * If non-canonical or not valid, return `undefined`.
1051
+ * If not valid, return `"error"`.
1052
+ * If non-canonical, return `undefined`.
1053
+ * If the type is not known, return `"unknown"`.
795
1054
  * :::
796
1055
  *
797
1056
  */
798
- get domain(): BoxedDomain | undefined;
799
- /** Modify the domain of a symbol.
800
- *
801
- * :::info[Note]
802
- * If non-canonical does nothing
803
- * :::
804
- *
805
- */
806
- set domain(domain: DomainExpression | BoxedDomain | undefined);
1057
+ get type(): Type;
1058
+ set type(type: Type);
807
1059
  /** `true` if the value of this expression is a number.
808
1060
  *
809
- * `isExtendedComplex || isNaN` = `isReal || isImaginary || isInfinity || isNaN`
810
1061
  *
811
1062
  * Note that in a fateful twist of cosmic irony, `NaN` ("Not a Number")
812
1063
  * **is** a number.
813
1064
  *
814
- * @category Domain Properties
1065
+ * If `isNumber` is `true`, this indicates that evaluating the expression
1066
+ * will return a number.
1067
+ *
1068
+ * This does not indicate that the expression is a number literal. To check
1069
+ * if the expression is a number literal, use `expr.isNumberLiteral`.
1070
+ *
1071
+ * For example, the expression `["Add", 1, "x"]` is a number if "x" is a
1072
+ * number and `expr.isNumber` is `true`, but `isNumberLiteral` is `false`.
1073
+ *
1074
+ * @category Type Properties
815
1075
  */
816
1076
  readonly isNumber: boolean | undefined;
817
- /** The value of this expression is an element of the set ℤ: ...,-2, -1, 0, 1, 2...
1077
+ /**
1078
+ *
1079
+ * The value of this expression is an element of the set ℤ: ...,-2, -1, 0, 1, 2...
818
1080
  *
1081
+ * Note that ±∞ and NaN are not integers.
819
1082
  *
820
- * @category Domain Properties
1083
+ * @category Type Properties
821
1084
  *
822
1085
  */
823
1086
  readonly isInteger: boolean | undefined;
@@ -825,75 +1088,107 @@ export interface BoxedExpression {
825
1088
  *
826
1089
  * Note that every integer is also a rational.
827
1090
  *
1091
+ * This is equivalent to `this.type === "rational" || this.type === "integer"`
828
1092
  *
829
- * @category Domain Properties
1093
+ * Note that ±∞ and NaN are not rationals.
1094
+ *
1095
+ * @category Type Properties
830
1096
  *
831
1097
  */
832
1098
  readonly isRational: boolean | undefined;
833
1099
  /**
834
- * The value of this expression is a number that is the root of a non-zero
835
- * univariate polynomial with rational coefficients.
1100
+ * The value of this expression is a real number.
836
1101
  *
837
- * All integers and rational numbers are algebraic.
1102
+ * This is equivalent to `this.type === "rational" || this.type === "integer" || this.type === "real"`
838
1103
  *
839
- * Transcendental numbers, such as \\( \pi \\) or \\( e \\) are not algebraic.
1104
+ * Note that ±∞ and NaN are not real numbers.
840
1105
  *
1106
+ * @category Type Properties
1107
+ */
1108
+ readonly isReal: boolean | undefined;
1109
+ /** Mathematical equality (strong equality), that is the value
1110
+ * of this expression and the value of `other` are numerically equal.
841
1111
  *
842
- * @category Domain Properties
1112
+ * Both expressions are evaluated and the result is compared numerically.
843
1113
  *
844
- */
845
- readonly isAlgebraic: boolean | undefined;
846
- /**
847
- * The value of this expression is real number: finite and not imaginary.
1114
+ * Numbers whose difference is less than `engine.tolerance` are
1115
+ * considered equal. This tolerance is set when the `engine.precision` is
1116
+ * changed to be such that the last two digits are ignored.
848
1117
  *
849
- * `isFinite && !isImaginary`
1118
+ * The evaluations may be expensive operations. Other options to consider
1119
+ * to compare two expressions include:
1120
+ * - `expr.isSame(other)` for a structural comparison
1121
+ * - `expr.is(other)` for a comparison of a number literal
850
1122
  *
1123
+ * ## Examples
851
1124
  *
852
- * @category Domain Properties
853
- */
854
- readonly isReal: boolean | undefined;
855
- /** Real or ±Infinity
1125
+ * ```js
1126
+ * let expr = ce.parse('2 + 2');
1127
+ * console.log(expr.isEqual(4)); // true
1128
+ * console.log(expr.isSame(ce.parse(4))); // false
1129
+ * console.log(expr.is(4)); // false
856
1130
  *
857
- * `isReal || isInfinity`
1131
+ * expr = ce.parse('4');
1132
+ * console.log(expr.isEqual(4)); // true
1133
+ * console.log(expr.isSame(ce.parse(4))); // true
1134
+ * console.log(expr.is(4)); // true (fastest)
858
1135
  *
1136
+ * ```
859
1137
  *
860
- * @category Domain Properties
1138
+ * @category Relational Operator
861
1139
  */
862
- readonly isExtendedReal: boolean | undefined;
1140
+ isEqual(other: number | BoxedExpression): boolean | undefined;
863
1141
  /**
864
- * The value of this expression is a number, but not `NaN` or any Infinity
865
- *
866
- * `isReal || isImaginary`
1142
+ * Return true if the expression is a collection: a list, a vector, a matrix, a map, a tuple, etc...
1143
+ */
1144
+ isCollection: boolean;
1145
+ /**
1146
+ * If this is a collection, return true if the `rhs` expression is in the
1147
+ * collection.
867
1148
  *
1149
+ * Return `undefined` if the membership cannot be determined.
1150
+ */
1151
+ contains(rhs: BoxedExpression): boolean | undefined;
1152
+ /**
1153
+ * If this is a collection, return the number of elements in the collection.
868
1154
  *
869
- * @category Domain Properties
1155
+ * If the collection is infinite, return `Infinity`.
870
1156
  *
871
1157
  */
872
- readonly isComplex: boolean | undefined;
873
- /** `isReal || isImaginary || isInfinity`
1158
+ get size(): number;
1159
+ /**
1160
+ * If this is a collection, return an iterator over the elements of the collection.
874
1161
  *
1162
+ * If `start` is not specified, start from the first element.
875
1163
  *
876
- * @category Domain Properties
1164
+ * If `count` is not specified or negative, return all the elements from `start` to the end.
1165
+ *
1166
+ * ```js
1167
+ * const expr = ce.parse('[1, 2, 3, 4]');
1168
+ * for (const e of expr.each()) {
1169
+ * console.log(e);
1170
+ * }
1171
+ * ```
877
1172
  */
878
- readonly isExtendedComplex: boolean | undefined;
879
- /** The value of this expression is a number with a imaginary part
1173
+ each: (start?: number, count?: number) => Iterator<BoxedExpression, undefined>;
1174
+ /** If this is an indexable collection, return the element at the specified
1175
+ * index.
880
1176
  *
1177
+ * If the index is negative, return the element at index `size() + index + 1`.
881
1178
  *
882
- * @category Domain Properties
883
1179
  */
884
- readonly isImaginary: boolean | undefined;
885
- /** Mathematical equality (strong equality), that is the value
886
- * of this expression and of `rhs` are numerically equal.
1180
+ at(index: number): BoxedExpression | undefined;
1181
+ /** If this is a map or a tuple, return the value of the corresponding key.
887
1182
  *
888
- * The numeric value of both expressions are compared.
1183
+ * If `key` is a `BoxedExpression`, it should be a string.
889
1184
  *
890
- * Numbers whose difference is less than `engine.tolerance` are
891
- * considered equal. This tolerance is set when the `engine.precision` is
892
- * changed to be such that the last two digits are ignored.
893
- *
894
- * @category Relational Operator
895
1185
  */
896
- isEqual(rhs: BoxedExpression): boolean;
1186
+ get(key: string | BoxedExpression): BoxedExpression | undefined;
1187
+ /**
1188
+ * If this is an indexable collection, return the index of the first element
1189
+ * that matches the target expression.
1190
+ */
1191
+ indexOf(expr: BoxedExpression): number | undefined;
897
1192
  }
898
1193
  /** A semi boxed expression is a MathJSON expression which can include some
899
1194
  * boxed terms.
@@ -903,7 +1198,7 @@ export interface BoxedExpression {
903
1198
  *
904
1199
  * @category Boxed Expression
905
1200
  */
906
- export type SemiBoxedExpression = number | string | Decimal | Complex | MathJsonNumber | MathJsonString | MathJsonSymbol | MathJsonFunction | MathJsonDictionary | SemiBoxedExpression[] | BoxedExpression;
1201
+ export type SemiBoxedExpression = number | bigint | string | BigNum | MathJsonNumber | MathJsonString | MathJsonSymbol | MathJsonFunction | readonly [MathJsonIdentifier, ...SemiBoxedExpression[]] | BoxedExpression;
907
1202
  /**
908
1203
  * @category Definitions
909
1204
  *
@@ -919,96 +1214,108 @@ export interface BoxedBaseDefinition {
919
1214
  * This field is usually undefined, but its value is set by `getDefinition()`
920
1215
  */
921
1216
  scope: RuntimeScope | undefined;
1217
+ collection?: Partial<CollectionHandlers>;
922
1218
  /** When the environment changes, for example the numerical precision,
923
1219
  * call `reset()` so that any cached values can be recalculated.
924
1220
  */
925
- reset(): any;
1221
+ reset(): void;
926
1222
  }
927
1223
  /**
928
- * Use `contravariant` for the arguments of a function.
929
- * Use `covariant` for the result of a function.
930
- * Use `bivariant` to check the domain matches exactly.
1224
+ * These handlers compare two expressions.
931
1225
  *
932
- * @category Boxed Expression
933
- */
934
- export type DomainCompatibility = 'covariant' | 'contravariant' | 'bivariant' | 'invariant';
935
- /** A domain constructor is the head of a domain expression.
1226
+ * If only one of the handlers is provided, the other is derived from it.
936
1227
  *
937
- * @category Boxed Expression
1228
+ * Having both may be useful if comparing non-equality is faster than equality.
938
1229
  *
939
- */
940
- export type DomainConstructor = 'FunctionOf' | 'ListOf' | 'DictionaryOf' | 'TupleOf' | 'Intersection' | 'Union' | 'OptArg' | 'VarArg' | 'Covariant' | 'Contravariant' | 'Bivariant' | 'Invariant';
941
- /**
942
- * @noInheritDoc
1230
+ * @category Definitions
943
1231
  *
944
- * @category Boxed Expression
945
1232
  */
946
- export interface BoxedDomain extends BoxedExpression {
947
- get canonical(): BoxedDomain;
948
- get json(): Expression;
949
- /** True if a valid domain, and compatible with `dom`
950
- * `kind` is '"covariant"' by default, i.e. `this <: dom`
951
- */
952
- isCompatible(dom: BoxedDomain | DomainLiteral, kind?: DomainCompatibility): boolean;
953
- get base(): DomainLiteral;
954
- get ctor(): DomainConstructor | null;
955
- get params(): DomainExpression[];
956
- readonly isNumeric: boolean;
957
- readonly isFunction: boolean;
958
- }
1233
+ export type EqHandlers = {
1234
+ eq: (a: BoxedExpression, b: BoxedExpression) => boolean | undefined;
1235
+ neq: (a: BoxedExpression, b: BoxedExpression) => boolean | undefined;
1236
+ };
959
1237
  /**
960
- * The handlers are the primitive operations that can be performed on
1238
+ * These handlers are the primitive operations that can be performed on
961
1239
  * collections.
962
1240
  *
963
1241
  * There are two types of collections:
1242
+ *
964
1243
  * - finite collections, such as lists, tuples, sets, matrices, etc...
965
1244
  * The `size()` handler of finite collections returns the number of elements
1245
+ *
966
1246
  * - infinite collections, such as sequences, ranges, etc...
967
1247
  * The `size()` handler of infinite collections returns `Infinity`
968
- * Infinite collections are not indexable, they have no `at()` handler.
1248
+ * Infinite collections are not indexable: they have no `at()` handler.
969
1249
  *
970
1250
  * @category Definitions
971
1251
  */
972
1252
  export type CollectionHandlers = {
1253
+ /** Return the number of elements in the collection.
1254
+ *
1255
+ * An empty collection has a size of 0.
1256
+ */
1257
+ size: (collection: BoxedExpression) => number;
1258
+ /**
1259
+ * Return `true` if the target
1260
+ * expression is in the collection, `false` otherwise.
1261
+ */
1262
+ contains: (collection: BoxedExpression, target: BoxedExpression) => boolean;
973
1263
  /** Return an iterator
974
1264
  * - start is optional and is a 1-based index.
975
1265
  * - if start is not specified, start from index 1
976
1266
  * - count is optional and is the number of elements to return
977
- * - if count is not specified or negative, return all the elements from start to the endna
1267
+ * - if count is not specified or negative, return all the elements from
1268
+ * start to the end
978
1269
  *
979
1270
  * If there is a `keys()` handler, there is no `iterator()` handler.
980
1271
  *
981
1272
  * @category Definitions
982
1273
  */
983
- iterator: (expr: BoxedExpression, start?: number, count?: number) => Iterator<BoxedExpression, undefined>;
984
- /** Return the element at the specified index.
1274
+ iterator: (collection: BoxedExpression, start?: number, count?: number) => Iterator<BoxedExpression, undefined>;
1275
+ /**
1276
+ * Return the element at the specified index.
1277
+ *
985
1278
  * The first element is `at(1)`, the last element is `at(-1)`.
1279
+ *
986
1280
  * If the index is &lt;0, return the element at index `size() + index + 1`.
987
- * The index can also be a string for example for dictionaries.
1281
+ *
1282
+ * The index can also be a string for example for maps. The set of valid keys
1283
+ * is returned by the `keys()` handler.
1284
+ *
988
1285
  * If the index is invalid, return `undefined`.
989
1286
  */
990
- at: (expr: BoxedExpression, index: number | string) => undefined | BoxedExpression;
991
- /** Return the number of elements in the collection.
992
- * An empty collection has a size of 0.
993
- */
994
- size: (expr: BoxedExpression) => number;
1287
+ at: (collection: BoxedExpression, index: number | string) => undefined | BoxedExpression;
995
1288
  /**
996
- * If the collection is indexed by strings, return the valid values
1289
+ * If the collection can be indexed by strings, return the valid values
997
1290
  * for the index.
998
1291
  */
999
- keys: (expr: BoxedExpression) => undefined | Iterator<string>;
1292
+ keys: (collection: BoxedExpression) => undefined | Iterable<string>;
1000
1293
  /**
1001
1294
  * Return the index of the first element that matches the target expression.
1295
+ *
1002
1296
  * The comparison is done using the `target.isEqual()` method.
1297
+ *
1003
1298
  * If the expression is not found, return `undefined`.
1299
+ *
1004
1300
  * If the expression is found, return the index, 1-based.
1005
- * If the expression is found multiple times, return the index of the first
1006
- * match.
1007
1301
  *
1008
- * From is the starting index for the search. If negative, start from the end
1009
- * and search backwards.
1302
+ * Return the index of the first match.
1303
+ *
1304
+ * `from` is the starting index for the search. If negative, start from
1305
+ * the end and search backwards.
1010
1306
  */
1011
- indexOf: (expr: BoxedExpression, target: BoxedExpression, from?: number) => number | string | undefined;
1307
+ indexOf: (collection: BoxedExpression, target: BoxedExpression, from?: number) => number | undefined;
1308
+ /**
1309
+ * Return `true` if all the elements of `target` are in `expr`.
1310
+ * Both `expr` and `target` are collections.
1311
+ * If strict is `true`, the subset must be strict, that is, `expr` must
1312
+ * have more elements than `target`.
1313
+ */
1314
+ subsetOf: (collection: BoxedExpression, target: BoxedExpression, strict: boolean) => boolean;
1315
+ /** Return the sign of all the elements of the collection. */
1316
+ eltsgn: (collection: BoxedExpression) => Sign | undefined;
1317
+ /** Return the widest type of all the elements in the collection */
1318
+ elttype: (collection: BoxedExpression) => Type | undefined;
1012
1319
  };
1013
1320
  /**
1014
1321
  * A function definition can have some flags to indicate specific
@@ -1016,6 +1323,17 @@ export type CollectionHandlers = {
1016
1323
  * @category Definitions
1017
1324
  */
1018
1325
  export type FunctionDefinitionFlags = {
1326
+ /**
1327
+ * If `true`, the arguments of the functions are held unevaluated.
1328
+ *
1329
+ * It will be up to the `evaluate()` handler to evaluate the arguments as
1330
+ * needed. This is conveninent to pass symbolic expressions as arguments
1331
+ * to functions without having to explicitly use a `Hold` expression.
1332
+ *
1333
+ * This also applies to the `canonical()` handler.
1334
+ *
1335
+ */
1336
+ hold: boolean;
1019
1337
  /** If `true`, the function is applied element by element to lists, matrices
1020
1338
  * (`["List"]` or `["Tuple"]` expressions) and equations (relational
1021
1339
  * operators).
@@ -1034,25 +1352,15 @@ export type FunctionDefinitionFlags = {
1034
1352
  * **Default**: `false`
1035
1353
  */
1036
1354
  commutative: boolean;
1037
- /** If `true`, when the function is univariate, `["f", ["Add", x, c]]` where `c`
1038
- * is constant, is simplified to `["Add", ["f", x], c]`.
1039
- *
1040
- * When the function is multivariate, additivity is considered only on the
1041
- * first argument: `["f", ["Add", x, c], y]` simplifies to `["Add", ["f", x, y], c]`.
1042
- *
1043
- * For example, `Log` is additive.
1044
- *
1045
- * **Default**: `false`
1046
- */
1047
- /** If `true`, when the function is univariate, `["f", ["Multiply", x, y]]`
1048
- * simplifies to `["Multiply", ["f", x], ["f", y]]`.
1355
+ /**
1356
+ * If `commutative` is `true`, the order of the arguments is determined by
1357
+ * this function.
1049
1358
  *
1050
- * When the function is multivariate, multiplicativity is considered only on the
1051
- * first argument: `["f", ["Multiply", x, y], z]` simplifies to
1052
- * `["Multiply", ["f", x, z], ["f", y, z]]`
1359
+ * If the function is not provided, the arguments are ordered by the
1360
+ * default order of the arguments.
1053
1361
  *
1054
- * **Default**: `false`
1055
1362
  */
1363
+ commutativeOrder: ((a: BoxedExpression, b: BoxedExpression) => number) | undefined;
1056
1364
  /** If `true`, when the function is univariate, `["f", ["Multiply", x, c]]`
1057
1365
  * simplifies to `["Multiply", ["f", x], c]` where `c` is constant
1058
1366
  *
@@ -1085,19 +1393,6 @@ export type FunctionDefinitionFlags = {
1085
1393
  * **Default:** `true`
1086
1394
  */
1087
1395
  pure: boolean;
1088
- /**
1089
- * An inert function evaluates directly to one of its argument, typically
1090
- * the first one. They may be used to provide formating hints, but do
1091
- * not affect simplification or evaluation.
1092
- *
1093
- * **Default:** false
1094
- */
1095
- inert: boolean;
1096
- /**
1097
- * All the arguments of a numeric function are numeric,
1098
- * and its value is numeric.
1099
- */
1100
- numeric: boolean;
1101
1396
  };
1102
1397
  /** @category Compiling */
1103
1398
  export type CompiledExpression = {
@@ -1105,34 +1400,35 @@ export type CompiledExpression = {
1105
1400
  [symbol: string]: BoxedExpression;
1106
1401
  }) => number | BoxedExpression;
1107
1402
  };
1108
- /**
1109
- * @category Definitions
1110
- *
1111
- */
1112
- export type BoxedFunctionSignature = {
1113
- inferredSignature: boolean;
1114
- params: BoxedDomain[];
1115
- optParams: BoxedDomain[];
1116
- restParam?: BoxedDomain;
1117
- result: BoxedDomain | ((ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedDomain | null | undefined);
1118
- canonical?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | null;
1119
- simplify?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined;
1120
- evaluate?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined;
1121
- N?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined;
1122
- evalDimension?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression;
1123
- sgn?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => -1 | 0 | 1 | undefined;
1124
- compile?: (expr: BoxedExpression) => CompiledExpression;
1125
- };
1126
1403
  /** @category Definitions */
1127
1404
  export type Hold = 'none' | 'all' | 'first' | 'rest' | 'last' | 'most';
1128
1405
  /**
1129
1406
  * @category Definitions
1130
1407
  *
1131
1408
  */
1132
- export type BoxedFunctionDefinition = BoxedBaseDefinition & Partial<CollectionHandlers> & FunctionDefinitionFlags & {
1409
+ export type BoxedFunctionDefinition = BoxedBaseDefinition & FunctionDefinitionFlags & {
1133
1410
  complexity: number;
1134
- hold: Hold;
1135
- signature: BoxedFunctionSignature;
1411
+ hold: boolean;
1412
+ inferredSignature: boolean;
1413
+ signature: Type;
1414
+ type?: (ops: ReadonlyArray<BoxedExpression>, options: {
1415
+ engine: IComputeEngine;
1416
+ }) => Type | TypeString | undefined;
1417
+ sgn?: (ops: ReadonlyArray<BoxedExpression>, options: {
1418
+ engine: IComputeEngine;
1419
+ }) => Sign | undefined;
1420
+ eq?: (a: BoxedExpression, b: BoxedExpression) => boolean | undefined;
1421
+ neq?: (a: BoxedExpression, b: BoxedExpression) => boolean | undefined;
1422
+ canonical?: (ops: ReadonlyArray<BoxedExpression>, options: {
1423
+ engine: IComputeEngine;
1424
+ }) => BoxedExpression | null;
1425
+ evaluate?: (ops: ReadonlyArray<BoxedExpression>, options: EvaluateOptions & {
1426
+ engine: IComputeEngine;
1427
+ }) => BoxedExpression | undefined;
1428
+ evalDimension?: (ops: ReadonlyArray<BoxedExpression>, options: {
1429
+ engine: IComputeEngine;
1430
+ }) => BoxedExpression;
1431
+ compile?: (expr: BoxedExpression) => CompiledExpression;
1136
1432
  };
1137
1433
  /**
1138
1434
  * @category Definitions
@@ -1140,7 +1436,7 @@ export type BoxedFunctionDefinition = BoxedBaseDefinition & Partial<CollectionHa
1140
1436
  */
1141
1437
  export type SymbolAttributes = {
1142
1438
  /**
1143
- * If `true` the value of the symbol is constant. The value or domain of
1439
+ * If `true` the value of the symbol is constant. The value or type of
1144
1440
  * symbols with this attribute set to `true` cannot be changed.
1145
1441
  *
1146
1442
  * If `false`, the symbol is a variable.
@@ -1154,61 +1450,36 @@ export type SymbolAttributes = {
1154
1450
 
1155
1451
  <div className="symbols-table">
1156
1452
 
1157
- | Operation | `"never"` | `"simplify"` | `"evaluate"` | `"N"` |
1158
- | :--- | :----- |
1159
- | `canonical()`| (X) | | | |
1160
- | `simplify()` | (X) | (X) | | |
1161
- | `evaluate()` | (X) | (X) | (X) | |
1162
- | `"N()"` | (X) | (X) | (X) | (X) |
1453
+ | Operation | `"never"` | `"evaluate"` | `"N"` |
1454
+ | :--- | :-----: | :----: | :---: |
1455
+ | `canonical()` | (X) | | |
1456
+ | `evaluate()` | (X) | (X) | |
1457
+ | `"N()"` | (X) | (X) | (X) |
1163
1458
 
1164
1459
  </div>
1165
1460
 
1166
1461
  * Some examples:
1167
- * - `i` has `holdUntil: 'never'`
1168
- * - `GoldenRatio` has `holdUntil: 'simplify'` (symbolic constant)
1462
+ * - `ImaginaryUnit` has `holdUntil: 'never'`: it is substituted during canonicalization
1169
1463
  * - `x` has `holdUntil: 'evaluate'` (variables)
1170
1464
  * - `Pi` has `holdUntil: 'N'` (special numeric constant)
1171
1465
  *
1172
1466
  * **Default:** `evaluate`
1173
1467
  */
1174
- holdUntil: 'never' | 'simplify' | 'evaluate' | 'N';
1468
+ holdUntil: 'never' | 'evaluate' | 'N';
1175
1469
  };
1176
1470
  /**
1177
- * When used in a `SymbolDefinition`, these flags are optional.
1471
+ * When used in a `SymbolDefinition` or `Functiondefinition` these flags
1472
+ * provide additional information about the value of the symbol or function.
1178
1473
  *
1179
1474
  * If provided, they will override the value derived from
1180
1475
  * the symbol's value.
1181
1476
  *
1182
- * For example, it might be useful to override `algebraic = false`
1183
- * for a transcendental number.
1184
- *
1185
1477
  * @category Definitions
1186
1478
  */
1187
1479
  export type NumericFlags = {
1188
- number: boolean | undefined;
1189
- integer: boolean | undefined;
1190
- rational: boolean | undefined;
1191
- algebraic: boolean | undefined;
1192
- real: boolean | undefined;
1193
- extendedReal: boolean | undefined;
1194
- complex: boolean | undefined;
1195
- extendedComplex: boolean | undefined;
1196
- imaginary: boolean | undefined;
1197
- positive: boolean | undefined;
1198
- nonPositive: boolean | undefined;
1199
- negative: boolean | undefined;
1200
- nonNegative: boolean | undefined;
1201
- zero: boolean | undefined;
1202
- notZero: boolean | undefined;
1203
- one: boolean | undefined;
1204
- negativeOne: boolean | undefined;
1205
- infinity: boolean | undefined;
1206
- NaN: boolean | undefined;
1207
- finite: boolean | undefined;
1480
+ sgn: Sign | undefined;
1208
1481
  even: boolean | undefined;
1209
1482
  odd: boolean | undefined;
1210
- prime: boolean | undefined;
1211
- composite: boolean | undefined;
1212
1483
  };
1213
1484
  /**
1214
1485
  * @noInheritDoc
@@ -1216,30 +1487,117 @@ export type NumericFlags = {
1216
1487
  */
1217
1488
  export interface BoxedSymbolDefinition extends BoxedBaseDefinition, SymbolAttributes, Partial<NumericFlags> {
1218
1489
  get value(): BoxedExpression | undefined;
1219
- set value(val: SemiBoxedExpression | number | undefined);
1220
- domain: BoxedDomain | undefined;
1221
- inferredDomain: boolean;
1490
+ set value(val: BoxedExpression | number | undefined);
1491
+ readonly isFunction: boolean;
1492
+ readonly isConstant: boolean;
1493
+ eq?: (a: BoxedExpression) => boolean | undefined;
1494
+ neq?: (a: BoxedExpression) => boolean | undefined;
1495
+ cmp?: (a: BoxedExpression) => '=' | '>' | '<' | undefined;
1496
+ inferredType: boolean;
1497
+ type: Type;
1222
1498
  }
1499
+ /**
1500
+ * Given an expression and set of wildcards, return a new expression.
1501
+ *
1502
+ * For example:
1503
+ *
1504
+ * ```ts
1505
+ * {
1506
+ * match: '_x',
1507
+ * replace: (expr, {_x}) => { return ['Add', 1, _x] }
1508
+ * }
1509
+ * ```
1510
+ *
1511
+ * @category Rules */
1512
+ export type RuleReplaceFunction = (expr: BoxedExpression, wildcards: BoxedSubstitution) => BoxedExpression | undefined;
1223
1513
  /** @category Rules */
1224
- export type PatternReplaceFunction = (expr: BoxedExpression, wildcards: BoxedSubstitution) => BoxedExpression;
1514
+ export type RuleConditionFunction = (wildcards: BoxedSubstitution, ce: IComputeEngine) => boolean;
1225
1515
  /** @category Rules */
1226
- export type PatternConditionFunction = (wildcards: BoxedSubstitution, ce: IComputeEngine) => boolean;
1516
+ export type RuleFunction = (expr: BoxedExpression) => undefined | BoxedExpression | RuleStep;
1517
+ export declare function isRuleStep(x: any): x is RuleStep;
1227
1518
  /**
1228
- * @noInheritDoc
1519
+ * A rule describes how to modify an expressions that matches a pattern `match`
1520
+ * into a new expression `replace`.
1229
1521
  *
1230
- * @category Pattern Matching
1522
+ * - `x-1` \( \to \) `1-x`
1523
+ * - `(x+1)(x-1)` \( \to \) `x^2-1
1524
+ *
1525
+ * The patterns can be expressed as LaTeX strings or a MathJSON expressions.
1526
+ *
1527
+ * As a shortcut, a rule can be defined as a LaTeX string: `x-1 -> 1-x`.
1528
+ * The expression to the left of `->` is the `match` and the expression to the
1529
+ * right is the `replace`. When using LaTeX strings, single character variables
1530
+ * are assumed to be wildcards.
1531
+ *
1532
+ * When using MathJSON expressions, anonymous wildcards (`_`) will match any
1533
+ * expression. Named wildcards (`_x`, `_a`, etc...) will match any expression
1534
+ * and bind the expression to the wildcard name.
1535
+ *
1536
+ * In addition the sequence wildcard (`__1`, `__a`, etc...) will match
1537
+ * a sequence of one or more expressions, and bind the sequence to the
1538
+ * wildcard name.
1539
+ *
1540
+ * Sequence wildcards are useful when the number of elements in the sequence
1541
+ * is not known in advance. For example, in a sum, the number of terms is
1542
+ * not known in advance. ["Add", 0, `__a`] will match two or more terms and
1543
+ * the `__a` wildcard will be a sequence of the matchign terms.
1544
+ *
1545
+ * If `exact` is false, the rule will match variants.
1546
+ *
1547
+ * For example 'x' will match 'a + x', 'x' will match 'ax', etc...
1548
+ *
1549
+ * For simplification rules, you generally want `exact` to be true, but
1550
+ * to solve equations, you want it to be false. Default to true.
1551
+ *
1552
+ * When set to false, infinite recursion is possible.
1553
+ *
1554
+ * @category Rules
1231
1555
  */
1232
- export type Pattern = BoxedExpression;
1233
- /** @category Rules */
1556
+ export type Rule = string | RuleFunction | {
1557
+ match?: LatexString | SemiBoxedExpression | Pattern;
1558
+ replace: LatexString | SemiBoxedExpression | RuleReplaceFunction | RuleFunction;
1559
+ condition?: LatexString | RuleConditionFunction;
1560
+ useVariations?: boolean;
1561
+ id?: string;
1562
+ };
1563
+ /**
1564
+ *
1565
+ * If the `match` property is `undefined`, all expressions match this rule
1566
+ * and `condition` should also be `undefined`. The `replace` property should
1567
+ * be a `BoxedExpression` or a `RuleFunction`, and further filtering can be
1568
+ * done in the `replace` function.
1569
+ *
1570
+ * @category Rules */
1234
1571
  export type BoxedRule = {
1235
- match: Pattern;
1236
- replace: BoxedExpression | PatternReplaceFunction;
1237
- condition: undefined | PatternConditionFunction;
1238
- priority: number;
1572
+ /** @internal */
1573
+ readonly _tag: 'boxed-rule';
1574
+ match: undefined | Pattern;
1575
+ replace: BoxedExpression | RuleReplaceFunction | RuleFunction;
1576
+ condition: undefined | RuleConditionFunction;
1577
+ useVariations?: boolean;
1239
1578
  id?: string;
1240
1579
  };
1241
- /** @category Rules */
1242
- export type BoxedRuleSet = ReadonlySet<BoxedRule>;
1580
+ export declare function isBoxedRule(x: any): x is BoxedRule;
1581
+ export type RuleStep = {
1582
+ value: BoxedExpression;
1583
+ because: string;
1584
+ };
1585
+ export type RuleSteps = RuleStep[];
1586
+ /**
1587
+ * To create a BoxedRuleSet use the `ce.rules()` method.
1588
+ *
1589
+ * Do not create a `BoxedRuleSet` directly.
1590
+ *
1591
+ * @category Rules */
1592
+ export type BoxedRuleSet = {
1593
+ rules: ReadonlyArray<BoxedRule>;
1594
+ };
1595
+ /**
1596
+ * @noInheritDoc
1597
+ *
1598
+ * @category Pattern Matching
1599
+ */
1600
+ export type Pattern = BoxedExpression;
1243
1601
  /**
1244
1602
  * @category Boxed Expression
1245
1603
  *
@@ -1272,47 +1630,31 @@ export type BoxedSubstitution = Substitution<BoxedExpression>;
1272
1630
  */
1273
1631
  export type CanonicalForm = 'InvisibleOperator' | 'Number' | 'Multiply' | 'Add' | 'Power' | 'Divide' | 'Flatten' | 'Order';
1274
1632
  export type CanonicalOptions = boolean | CanonicalForm | CanonicalForm[];
1275
- /** @category Boxed Expression */
1276
- export type DomainLiteral = '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';
1277
- /** @category Boxed Expression */
1278
- export type DomainExpression<T = SemiBoxedExpression> = 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>[]];
1279
1633
  /** Options for `BoxedExpression.simplify()`
1280
1634
  *
1281
1635
  * @category Compute Engine
1282
1636
  */
1283
1637
  export type SimplifyOptions = {
1284
- recursive?: boolean;
1285
- rules?: BoxedRuleSet;
1638
+ /**
1639
+ * The set of rules to apply. If `null`, use no rules. If not provided,
1640
+ * use the default simplification rules.
1641
+ */
1642
+ rules?: null | Rule | ReadonlyArray<BoxedRule | Rule> | BoxedRuleSet;
1643
+ /**
1644
+ * Use this cost function to determine if a simplification is worth it.
1645
+ *
1646
+ * If not provided, `ce.costFunction`, the cost function of the engine is
1647
+ * used.
1648
+ */
1649
+ costFunction?: (expr: BoxedExpression) => number;
1286
1650
  };
1287
1651
  /** Options for `BoxedExpression.evaluate()`
1288
1652
  *
1289
1653
  * @category Boxed Expression
1290
1654
  */
1291
1655
  export type EvaluateOptions = {
1292
- numericMode?: boolean;
1656
+ numericApproximation?: boolean;
1293
1657
  };
1294
- /** Options for `BoxedExpression.N()`
1295
- *
1296
- * @category Boxed Expression
1297
- */
1298
- export type NOptions = {};
1299
- /**
1300
- * The numeric evaluation mode:
1301
- *
1302
- <div className="symbols-table">
1303
-
1304
- | Mode | |
1305
- | :--- | :----- |
1306
- | `"auto"`| Use bignum or complex numbers. |
1307
- | `"machine"` | **IEEE 754-2008**, 64-bit floating point numbers: 52-bit mantissa, about 15 digits of precision |
1308
- | `"bignum"` | Arbitrary precision floating point numbers, as provided by the "decimal.js" library |
1309
- | `"complex"` | Complex number represented by two machine numbers, a real and an imaginary part, as provided by the "complex.js" library |
1310
-
1311
- </div>
1312
-
1313
- * @category Compute Engine
1314
- */
1315
- export type NumericMode = 'auto' | 'machine' | 'bignum' | 'complex';
1316
1658
  /**
1317
1659
  * Metadata that can be associated with a `BoxedExpression`
1318
1660
  *
@@ -1335,22 +1677,19 @@ export type Metadata = {
1335
1677
  */
1336
1678
  export type AngularUnit = 'rad' | 'deg' | 'grad' | 'turn';
1337
1679
  /** @category Compute Engine */
1338
- export type ArrayValue = boolean | number | string | Decimal | Complex | BoxedExpression | undefined;
1680
+ export type ArrayValue = boolean | number | string | BigNum | BoxedExpression | undefined;
1339
1681
  /** @category Assumptions */
1340
1682
  export type AssumeResult = 'internal-error' | 'not-a-predicate' | 'contradiction' | 'tautology' | 'ok';
1341
1683
  /** @category Compute Engine */
1342
- export type AssignValue = boolean | number | string | Decimal | Complex | LatexString | SemiBoxedExpression | ((ce: IComputeEngine, args: any) => BoxedExpression) | undefined;
1684
+ export type AssignValue = boolean | number | string | LatexString | SemiBoxedExpression | ((args: ReadonlyArray<BoxedExpression>, options: EvaluateOptions & {
1685
+ engine: IComputeEngine;
1686
+ }) => BoxedExpression) | undefined;
1343
1687
  /** @internal */
1344
- export interface IComputeEngine {
1688
+ export interface IComputeEngine extends IBigNum {
1345
1689
  latexDictionary: readonly LatexDictionaryEntry[];
1346
1690
  /** @private */
1347
1691
  indexedLatexDictionary: IndexedLatexDictionary;
1348
1692
  decimalSeparator: LatexString;
1349
- readonly Anything: BoxedDomain;
1350
- readonly Void: BoxedDomain;
1351
- readonly Strings: BoxedDomain;
1352
- readonly Booleans: BoxedDomain;
1353
- readonly Numbers: BoxedDomain;
1354
1693
  readonly True: BoxedExpression;
1355
1694
  readonly False: BoxedExpression;
1356
1695
  readonly Pi: BoxedExpression;
@@ -1366,54 +1705,63 @@ export interface IComputeEngine {
1366
1705
  readonly NegativeInfinity: BoxedExpression;
1367
1706
  readonly ComplexInfinity: BoxedExpression;
1368
1707
  /** @internal */
1369
- readonly _BIGNUM_NAN: Decimal;
1708
+ readonly _BIGNUM_NAN: BigNum;
1370
1709
  /** @internal */
1371
- readonly _BIGNUM_ZERO: Decimal;
1710
+ readonly _BIGNUM_ZERO: BigNum;
1372
1711
  /** @internal */
1373
- readonly _BIGNUM_ONE: Decimal;
1712
+ readonly _BIGNUM_ONE: BigNum;
1374
1713
  /** @internal */
1375
- readonly _BIGNUM_TWO: Decimal;
1714
+ readonly _BIGNUM_TWO: BigNum;
1376
1715
  /** @internal */
1377
- readonly _BIGNUM_HALF: Decimal;
1716
+ readonly _BIGNUM_HALF: BigNum;
1378
1717
  /** @internal */
1379
- readonly _BIGNUM_PI: Decimal;
1718
+ readonly _BIGNUM_PI: BigNum;
1380
1719
  /** @internal */
1381
- readonly _BIGNUM_NEGATIVE_ONE: Decimal;
1720
+ readonly _BIGNUM_NEGATIVE_ONE: BigNum;
1382
1721
  /** The current scope */
1383
1722
  context: RuntimeScope | null;
1384
1723
  /** Absolute time beyond which evaluation should not proceed
1385
1724
  * @internal
1386
1725
  */
1387
1726
  deadline?: number;
1727
+ generation: number;
1388
1728
  /** @hidden */
1389
1729
  readonly timeLimit: number;
1390
1730
  /** @hidden */
1391
1731
  readonly iterationLimit: number;
1392
1732
  /** @hidden */
1393
1733
  readonly recursionLimit: number;
1394
- numericMode: NumericMode;
1395
- tolerance: number;
1396
- angularUnit: AngularUnit;
1397
1734
  chop(n: number): number;
1398
- chop(n: Decimal): Decimal | 0;
1399
- chop(n: Complex): Complex | 0;
1400
- chop(n: number | Decimal | Complex): number | Decimal | Complex;
1401
- bignum: (a: Decimal.Value | bigint) => Decimal;
1402
- isBignum(a: unknown): a is Decimal;
1735
+ chop(n: BigNum): BigNum | 0;
1736
+ chop(n: number | BigNum): number | BigNum;
1737
+ bignum: (a: string | number | bigint | BigNum) => BigNum;
1403
1738
  complex: (a: number | Complex, b?: number) => Complex;
1404
- isComplex(a: unknown): a is Complex;
1405
- set precision(p: number | 'machine');
1739
+ /** @internal */
1740
+ _numericValue(value: number | bigint | OneOf<[BigNum | NumericValueData | ExactNumericValueData]>): NumericValue;
1741
+ /** If the precision is set to `machine`, floating point numbers
1742
+ * are represented internally as a 64-bit floating point number (as
1743
+ * per IEEE 754-2008), with a 52-bit mantissa, which gives about 15
1744
+ * digits of precision.
1745
+ *
1746
+ * If the precision is set to `auto`, the precision is set to 300 digits.
1747
+ *
1748
+ */
1749
+ set precision(p: number | 'machine' | 'auto');
1406
1750
  get precision(): number;
1751
+ tolerance: number;
1752
+ angularUnit: AngularUnit;
1407
1753
  costFunction: (expr: BoxedExpression) => number;
1408
1754
  strict: boolean;
1409
- box(expr: Decimal | Complex | [num: number, denom: number] | SemiBoxedExpression, options?: {
1755
+ box(expr: NumericValue | SemiBoxedExpression, options?: {
1410
1756
  canonical?: CanonicalOptions;
1757
+ structural?: boolean;
1411
1758
  }): BoxedExpression;
1412
- function(head: string | BoxedExpression, ops: ReadonlyArray<SemiBoxedExpression>, options?: {
1759
+ function(name: string, ops: ReadonlyArray<SemiBoxedExpression>, options?: {
1413
1760
  metadata?: Metadata;
1414
1761
  canonical?: CanonicalOptions;
1762
+ structural?: boolean;
1415
1763
  }): BoxedExpression;
1416
- number(value: number | bigint | string | MathJsonNumber | Decimal | Complex | Rational, options?: {
1764
+ number(value: number | bigint | string | NumericValue | MathJsonNumber | BigNum | Complex | Rational, options?: {
1417
1765
  metadata?: Metadata;
1418
1766
  canonical?: CanonicalOptions;
1419
1767
  }): BoxedExpression;
@@ -1422,26 +1770,23 @@ export interface IComputeEngine {
1422
1770
  canonical?: CanonicalOptions;
1423
1771
  }): BoxedExpression;
1424
1772
  string(s: string, metadata?: Metadata): BoxedExpression;
1425
- domain(domain: BoxedDomain | DomainExpression, metadata?: Metadata): BoxedDomain;
1426
- error(message: MathJsonIdentifier | [MathJsonIdentifier, ...ReadonlyArray<SemiBoxedExpression>], where?: SemiBoxedExpression): BoxedExpression;
1427
- domainError(expectedDomain: BoxedDomain | DomainLiteral, actualDomain: undefined | BoxedDomain, where?: SemiBoxedExpression): BoxedExpression;
1773
+ error(message: string | string[], where?: string): BoxedExpression;
1774
+ typeError(expectedType: Type, actualType: undefined | Type, where?: SemiBoxedExpression): BoxedExpression;
1428
1775
  hold(expr: SemiBoxedExpression): BoxedExpression;
1429
- add(...ops: ReadonlyArray<BoxedExpression>): BoxedExpression;
1430
- mul(...ops: ReadonlyArray<BoxedExpression>): BoxedExpression;
1431
- pow(base: BoxedExpression, exponent: number | Rational | BoxedExpression): BoxedExpression;
1432
- sqrt(base: BoxedExpression): BoxedExpression;
1433
- inv(expr: BoxedExpression): BoxedExpression;
1434
- neg(expr: BoxedExpression): BoxedExpression;
1435
- div(num: BoxedExpression, denom: BoxedExpression): BoxedExpression;
1436
- pair(first: BoxedExpression, second: BoxedExpression, metadata?: Metadata): BoxedExpression;
1437
- tuple(elements: ReadonlyArray<number>, metadata?: Metadata): BoxedExpression;
1438
- tuple(elements: ReadonlyArray<BoxedExpression>, metadata?: Metadata): BoxedExpression;
1439
- array(elements: ArrayValue[] | ArrayValue[][], metadata?: Metadata): BoxedExpression;
1440
- rules(rules: Rule[]): BoxedRuleSet;
1776
+ tuple(...elements: ReadonlyArray<number>): BoxedExpression;
1777
+ tuple(...elements: ReadonlyArray<BoxedExpression>): BoxedExpression;
1778
+ rules(rules: Rule | ReadonlyArray<Rule | BoxedRule> | BoxedRuleSet | undefined | null, options?: {
1779
+ canonical?: boolean;
1780
+ }): BoxedRuleSet;
1781
+ /**
1782
+ * Return a set of built-in rules.
1783
+ */
1784
+ getRuleSet(id?: 'harmonization' | 'solve-univariate' | 'standard-simplification'): BoxedRuleSet | undefined;
1441
1785
  /**
1442
1786
  * This is a primitive to create a boxed function.
1443
1787
  *
1444
- * In general, consider using `ce.box()` or `canonicalXXX()` instead.
1788
+ * In general, consider using `ce.box()` or `ce.function()` or
1789
+ * `canonicalXXX()` instead.
1445
1790
  *
1446
1791
  * The caller must ensure that the arguments are in canonical form:
1447
1792
  * - arguments are `canonical()`
@@ -1450,7 +1795,7 @@ export interface IComputeEngine {
1450
1795
  *
1451
1796
  * @internal
1452
1797
  */
1453
- _fn(head: string | BoxedExpression, ops: ReadonlyArray<BoxedExpression>, options?: Metadata & {
1798
+ _fn(name: string, ops: ReadonlyArray<BoxedExpression>, options?: Metadata & {
1454
1799
  canonical?: boolean;
1455
1800
  }): BoxedExpression;
1456
1801
  parse(latex: null, options?: Partial<ParseLatexOptions> & {
@@ -1469,7 +1814,7 @@ export interface IComputeEngine {
1469
1814
  defineSymbol(name: string, def: SymbolDefinition): BoxedSymbolDefinition;
1470
1815
  lookupSymbol(name: string, wikidata?: string, scope?: RuntimeScope): undefined | BoxedSymbolDefinition;
1471
1816
  defineFunction(name: string, def: FunctionDefinition): BoxedFunctionDefinition;
1472
- lookupFunction(head: string | BoxedExpression, scope?: RuntimeScope | null): undefined | BoxedFunctionDefinition;
1817
+ lookupFunction(name: string, scope?: RuntimeScope | null): undefined | BoxedFunctionDefinition;
1473
1818
  assign(ids: {
1474
1819
  [id: string]: AssignValue;
1475
1820
  }): IComputeEngine;
@@ -1478,23 +1823,23 @@ export interface IComputeEngine {
1478
1823
  [id: string]: AssignValue;
1479
1824
  }, arg2?: AssignValue): IComputeEngine;
1480
1825
  declare(identifiers: {
1481
- [id: string]: BoxedDomain | DomainExpression | SymbolDefinition | FunctionDefinition;
1826
+ [id: string]: Type | TypeString | OneOf<[SymbolDefinition | FunctionDefinition]>;
1482
1827
  }): IComputeEngine;
1483
- declare(id: string, def: BoxedDomain | DomainExpression | SymbolDefinition | FunctionDefinition): IComputeEngine;
1828
+ declare(id: string, def: Type | TypeString | SymbolDefinition | FunctionDefinition): IComputeEngine;
1484
1829
  declare(arg1: string | {
1485
- [id: string]: BoxedDomain | DomainExpression | SymbolDefinition | FunctionDefinition;
1486
- }, arg2?: BoxedDomain | DomainExpression | SymbolDefinition | FunctionDefinition): IComputeEngine;
1487
- assume(predicate: SemiBoxedExpression): AssumeResult;
1830
+ [id: string]: Type | TypeString | OneOf<[SymbolDefinition | FunctionDefinition]>;
1831
+ }, arg2?: Type | OneOf<[SymbolDefinition | FunctionDefinition]>): IComputeEngine;
1832
+ assume(predicate: BoxedExpression): AssumeResult;
1488
1833
  forget(symbol?: string | string[]): void;
1489
1834
  get assumptions(): ExpressionMapInterface<boolean>;
1490
- ask(pattern: SemiBoxedExpression): BoxedSubstitution[];
1491
- verify(query: SemiBoxedExpression): boolean;
1835
+ ask(pattern: BoxedExpression): BoxedSubstitution[];
1836
+ verify(query: BoxedExpression): boolean;
1492
1837
  /** @internal */
1493
1838
  shouldContinueExecution(): boolean;
1494
1839
  /** @internal */
1495
1840
  checkContinueExecution(): void;
1496
1841
  /** @internal */
1497
- cache<T>(name: string, build: () => T, purge?: (T: any) => T | undefined): T;
1842
+ cache<T>(name: string, build: () => T, purge?: (t: T) => T | undefined): T;
1498
1843
  /** @internal */
1499
1844
  readonly stats: ComputeEngineStats;
1500
1845
  /** @internal */
@@ -1511,7 +1856,7 @@ export interface ComputeEngineStats {
1511
1856
  highwaterMark: number;
1512
1857
  }
1513
1858
  /**
1514
- * Options to control the serialization to MathJSON when using `BoxedExpression.json`.
1859
+ * Options to control the serialization to MathJSON when using `BoxedExpression.toMathJson()`.
1515
1860
  *
1516
1861
  * @category Compute Engine
1517
1862
  */
@@ -1538,7 +1883,7 @@ export type JsonSerializationOptions = {
1538
1883
  *
1539
1884
  * **Default**: `["all"]`
1540
1885
  */
1541
- shorthands: ('all' | 'number' | 'symbol' | 'function' | 'dictionary' | 'string')[];
1886
+ shorthands: ('all' | 'number' | 'symbol' | 'function' | 'string')[];
1542
1887
  /** A list of space separated keywords indicating which metadata should be
1543
1888
  * included in the MathJSON. If metadata is included, shorthand notation
1544
1889
  * is not used.
@@ -1572,10 +1917,16 @@ export type LatexString = string;
1572
1917
  /**
1573
1918
  * Control how a pattern is matched to an expression.
1574
1919
  *
1575
- * - `substitution`: if present, assumes these values for the named wildcards, and ensure that subsequent occurence of the same wildcard have the same value.
1576
- * - `recursive`: if true, match recursively, otherwise match only the top level.
1577
- * - `numericTolerance`: if present, the tolerance for numeric comparison.
1578
- * - `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]` matches `2`, with a value of `_a` of `0`. If true, the expression does not match.
1920
+ * - `substitution`: if present, assumes these values for the named wildcards,
1921
+ * and ensure that subsequent occurrence of the same wildcard have the same
1922
+ * value.
1923
+ * - `recursive`: if true, match recursively, otherwise match only the top
1924
+ * level.
1925
+ * - `exact`: if true, only match expressions that are structurally identical.
1926
+ * If false, match expressions that are structurally identical or equivalent.
1927
+ *
1928
+ * For example, when false, `["Add", '_a', 2]` matches `2`, with a value of
1929
+ * `_a` of `0`. If true, the expression does not match. **Default**: `true`
1579
1930
  *
1580
1931
  * @category Pattern Matching
1581
1932
  *
@@ -1583,20 +1934,21 @@ export type LatexString = string;
1583
1934
  export type PatternMatchOptions = {
1584
1935
  substitution?: BoxedSubstitution;
1585
1936
  recursive?: boolean;
1586
- numericTolerance?: number;
1587
- exact?: boolean;
1937
+ useVariations?: boolean;
1588
1938
  };
1589
1939
  /**
1590
1940
  * @category Boxed Expression
1591
1941
  *
1592
1942
  */
1593
1943
  export type ReplaceOptions = {
1594
- /** If `true`, apply replacement rules to all sub-expressions.
1944
+ /**
1945
+ * If `true`, apply replacement rules to all sub-expressions.
1946
+ *
1595
1947
  * If `false`, only consider the top-level expression.
1596
1948
  *
1597
1949
  * **Default**: `false`
1598
1950
  */
1599
- recursive?: boolean;
1951
+ recursive: boolean;
1600
1952
  /**
1601
1953
  * If `true`, stop after the first rule that matches.
1602
1954
  *
@@ -1604,57 +1956,50 @@ export type ReplaceOptions = {
1604
1956
  *
1605
1957
  * **Default**: `false`
1606
1958
  */
1607
- once?: boolean;
1959
+ once: boolean;
1960
+ /**
1961
+ * If `true` the rule will use some equivalent variations to match.
1962
+ *
1963
+ * For example when `useVariations` is true:
1964
+ * - `x` matches `a + x` with a = 0
1965
+ * - `x` matches `ax` with a = 1
1966
+ * - etc...
1967
+ *
1968
+ * Setting this to `true` can save time by condensing multiple rules
1969
+ * into one. This can be particularly useful when describing equations
1970
+ * solutions. However, it can lead to infinite recursion and should be
1971
+ * used with caution.
1972
+ *
1973
+ */
1974
+ useVariations: boolean;
1608
1975
  /**
1609
1976
  * If `iterationLimit` > 1, the rules will be repeatedly applied
1610
1977
  * until no rules apply, up to `maxIterations` times.
1611
1978
  *
1612
- * Note that if `once` is true, `maxIterations` has no effect.
1979
+ * Note that if `once` is true, `iterationLimit` has no effect.
1613
1980
  *
1614
1981
  * **Default**: `1`
1615
1982
  */
1616
- iterationLimit?: number;
1983
+ iterationLimit: number;
1984
+ /**
1985
+ * Indicate if the expression should be canonicalized after the replacement.
1986
+ * If not provided, the expression is canonicalized if the the expression
1987
+ * that matched the pattern is canonical.
1988
+ */
1989
+ canonical: CanonicalOptions;
1617
1990
  };
1618
1991
  /**
1619
1992
  * A substitution describes the values of the wildcards in a pattern so that
1620
1993
  * the pattern is equal to a target expression.
1621
1994
  *
1622
1995
  * A substitution can also be considered a more constrained version of a
1623
- * rule whose `lhs` is always a symbol.
1996
+ * rule whose `match` is always a symbol.
1624
1997
 
1625
1998
  * @category Boxed Expression
1626
1999
  */
1627
2000
  export type Substitution<T = SemiBoxedExpression> = {
1628
2001
  [symbol: string]: T;
1629
2002
  };
1630
- /**
1631
- * A rule describes how to modify an expressions that matches a pattern `match`
1632
- * into a new expression `replace`.
1633
- *
1634
- * `x-1` \( \to \) `1-x`
1635
- * `(x+1)(x-1)` \( \to \) `x^2-1
1636
- *
1637
- * The `match` pattern can be expressed as a LaTeX string or a
1638
- * MathJSON expression.
1639
- *
1640
- *
1641
- * Anonymous wildcards (`_`) will match any
1642
- * expression. Named wildcards (`_x`, `_a`, etc...) will match any expression
1643
- * and bind the expression to the wildcard name.
1644
- *
1645
- * In addition the sequence wildcard (`__1`, `__a`, etc...) will match
1646
- * a sequence of one or more expressions, and bind the sequence to the
1647
- * wildcard name.
1648
- *
1649
- * @category Rules
1650
- */
1651
- export type Rule = {
1652
- match: LatexString | SemiBoxedExpression | Pattern;
1653
- replace: LatexString | SemiBoxedExpression | PatternReplaceFunction;
1654
- condition?: LatexString | PatternConditionFunction;
1655
- priority?: number;
1656
- id?: string;
1657
- };
1658
2003
  /** @category Assumptions */
1659
2004
  export interface ExpressionMapInterface<U> {
1660
2005
  has(expr: BoxedExpression): boolean;
@@ -1673,7 +2018,7 @@ export interface ExpressionMapInterface<U> {
1673
2018
  *
1674
2019
  * @category Definitions
1675
2020
  */
1676
- export type RuntimeIdentifierDefinitions = Map<string, BoxedSymbolDefinition | BoxedFunctionDefinition>;
2021
+ export type RuntimeIdentifierDefinitions = Map<string, OneOf<[BoxedSymbolDefinition, BoxedFunctionDefinition]>>;
1677
2022
  /**
1678
2023
  * A scope is a set of names in a dictionary that are bound (defined) in
1679
2024
  * a MathJSON expression.
@@ -1725,13 +2070,13 @@ export type RuntimeScope = Scope & {
1725
2070
  assumptions: undefined | ExpressionMapInterface<boolean>;
1726
2071
  };
1727
2072
  /**
1728
- * A bound symbol (i.e. one with an associated definition) has either a domain
1729
- * (e.g. ∀ x ∈ ℝ), a value (x = 5) or both (π: value = 3.14... domain = TranscendentalNumbers)
2073
+ * A bound symbol (i.e. one with an associated definition) has either a type
2074
+ * (e.g. ∀ x ∈ ℝ), a value (x = 5) or both (π: value = 3.14... type = 'real')
1730
2075
  * @category Definitions
1731
2076
  */
1732
2077
  export type SymbolDefinition = BaseDefinition & Partial<SymbolAttributes> & {
1733
- domain?: DomainLiteral | BoxedDomain;
1734
- /** If true, the domain is inferred, and could be adjusted later
2078
+ type?: Type | TypeString;
2079
+ /** If true, the type is inferred, and could be adjusted later
1735
2080
  * as more information becomes available or if the symbol is explicitly
1736
2081
  * declared.
1737
2082
  */
@@ -1739,20 +2084,67 @@ export type SymbolDefinition = BaseDefinition & Partial<SymbolAttributes> & {
1739
2084
  /** `value` can be a JS function since for some constants, such as
1740
2085
  * `Pi`, the actual value depends on the `precision` setting of the
1741
2086
  * `ComputeEngine` and possible other environment settings */
1742
- value?: LatexString | SemiBoxedExpression | ((ce: IComputeEngine) => SemiBoxedExpression | null);
2087
+ value?: LatexString | SemiBoxedExpression | ((ce: IComputeEngine) => BoxedExpression | null);
1743
2088
  flags?: Partial<NumericFlags>;
2089
+ eq?: (a: BoxedExpression) => boolean | undefined;
2090
+ neq?: (a: BoxedExpression) => boolean | undefined;
2091
+ cmp?: (a: BoxedExpression) => '=' | '>' | '<' | undefined;
2092
+ collection?: Partial<CollectionHandlers>;
1744
2093
  };
1745
2094
  /**
1746
2095
  * Definition record for a function.
1747
2096
  * @category Definitions
1748
2097
  *
1749
2098
  */
1750
- export type FunctionDefinition = BaseDefinition & Partial<CollectionHandlers> & Partial<FunctionDefinitionFlags> & {
2099
+ export type FunctionDefinition = BaseDefinition & Partial<FunctionDefinitionFlags> & {
2100
+ /**
2101
+ * The function signature.
2102
+ *
2103
+ * If a `type` handler is provided, the return type of the function should
2104
+ * be a subtype of the return type in the signature.
2105
+ *
2106
+ */
2107
+ signature?: Type | TypeString;
2108
+ /**
2109
+ * The actual type of the result based on the arguments.
2110
+ *
2111
+ * Should be a subtype of the type indicated in the signature.
2112
+ *
2113
+ * Do not evaluate the arguments.
2114
+ *
2115
+ * The type of the arguments can be used to determine the type of the
2116
+ * result.
2117
+ *
2118
+ */
2119
+ type?: (ops: ReadonlyArray<BoxedExpression>, options: {
2120
+ engine: IComputeEngine;
2121
+ }) => Type;
2122
+ /** Return the sign of the function expression.
2123
+ *
2124
+ * If the sign cannot be determined, return `undefined`.
2125
+ *
2126
+ * When determining the sign, only literal values and the values of
2127
+ * symbols, if they are literals, should be considered.
2128
+ *
2129
+ * Do not evaluate the arguments.
2130
+ *
2131
+ * The type and sign of the arguments can be used to determine the sign.
2132
+ *
2133
+ */
2134
+ sgn?: (ops: ReadonlyArray<BoxedExpression>, options: {
2135
+ engine: IComputeEngine;
2136
+ }) => Sign | undefined;
2137
+ /** Return true of the function expression is even, false if it is odd and
2138
+ * undefined if it is neither.
2139
+ */
2140
+ even?: (ops: ReadonlyArray<BoxedExpression>, options: {
2141
+ engine: IComputeEngine;
2142
+ }) => boolean | undefined;
1751
2143
  /**
1752
2144
  * A number used to order arguments.
1753
2145
  *
1754
- * Argument with higher complexity are placed after arguments with lower
1755
- * complexity when ordered canonically in commutative functions.
2146
+ * Argument with higher complexity are placed after arguments with
2147
+ * lower complexity when ordered canonically in commutative functions.
1756
2148
  *
1757
2149
  * - Additive functions: 1000-1999
1758
2150
  * - Multiplicative functions: 2000-2999
@@ -1769,69 +2161,21 @@ export type FunctionDefinition = BaseDefinition & Partial<CollectionHandlers> &
1769
2161
  * **Default**: 100,000
1770
2162
  */
1771
2163
  complexity?: number;
1772
- /**
1773
- * - `"none"` Each of the arguments is evaluated (default)
1774
- * - `"all"` None of the arguments are evaluated and they are passed as is
1775
- * - `"first"` The first argument is not evaluated, the others are
1776
- * - `"rest"` The first argument is evaluated, the others aren't
1777
- * - `"last"`: The last argument is not evaluated, the others are
1778
- * - `"most"`: All the arguments are evaluated, except the last one
1779
- *
1780
- * **Default**: `"none"`
1781
- */
1782
- hold?: Hold;
1783
- signature: FunctionSignature;
1784
- };
1785
- /**
1786
- * @category Definitions
1787
- *
1788
- */
1789
- export type BaseDefinition = {
1790
- /** A short (about 1 line) description. May contain Markdown. */
1791
- description?: string | string[];
1792
- /** A URL pointing to more information about this symbol or head. */
1793
- url?: string;
1794
- /**
1795
- * A short string representing an entry in a wikibase.
1796
- *
1797
- * For example `Q167` is the [wikidata entry](https://www.wikidata.org/wiki/Q167)
1798
- * for the `Pi` constant.
1799
- */
1800
- wikidata?: string;
1801
- };
1802
- /**
1803
- * @category Definitions
1804
- *
1805
- */
1806
- export type FunctionSignature = {
1807
- /** The domain of this signature, a domain compatible with the `Functions`
1808
- * domain).
1809
- *
1810
- * @deprecated Use params, optParams, restParam and result instead
1811
- */
1812
- domain?: DomainExpression;
1813
- params?: DomainExpression[];
1814
- optParams?: DomainExpression[];
1815
- restParam?: DomainExpression;
1816
- /** The domain of the result of the function. Either a domain
1817
- * expression, or a function that returns a boxed domain.
1818
- */
1819
- result?: DomainExpression | ((ce: IComputeEngine, args: BoxedDomain[]) => BoxedDomain | null | undefined);
1820
2164
  /**
1821
2165
  * Return the canonical form of the expression with the arguments `args`.
1822
2166
  *
1823
2167
  * The arguments (`args`) may not be in canonical form. If necessary, they
1824
2168
  * can be put in canonical form.
1825
2169
  *
1826
- * This handler should validate the domain and number of the arguments.
2170
+ * This handler should validate the type and number of the arguments.
1827
2171
  *
1828
2172
  * If a required argument is missing, it should be indicated with a
1829
2173
  * `["Error", "'missing"]` expression. If more arguments than expected
1830
2174
  * are present, this should be indicated with an
1831
2175
  * ["Error", "'unexpected-argument'"]` error expression
1832
2176
  *
1833
- * If the domain of an argument is not compatible, it should be indicated
1834
- * with an `incompatible-domain` error.
2177
+ * If the type of an argument is not compatible, it should be indicated
2178
+ * with an `incompatible-type` error.
1835
2179
  *
1836
2180
  * `["Sequence"]` expressions are not folded and need to be handled
1837
2181
  * explicitly.
@@ -1840,9 +2184,6 @@ export type FunctionSignature = {
1840
2184
  * this handler should account for it. Notably, if it is commutative, the
1841
2185
  * arguments should be sorted in canonical order.
1842
2186
  *
1843
- * The handler can make transformations based on the value of the arguments
1844
- * that are exact and literal (i.e.
1845
- * `arg.numericValue !== null && arg.isExact`).
1846
2187
  *
1847
2188
  * Values of symbols should not be substituted, unless they have
1848
2189
  * a `holdUntil` attribute of `"never"`.
@@ -1858,35 +2199,9 @@ export type FunctionSignature = {
1858
2199
  * the handler should return `null`.
1859
2200
  *
1860
2201
  */
1861
- canonical?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | null;
1862
- /**
1863
- * Rewrite an expression into a simpler form.
1864
- *
1865
- * The arguments are in canonical form and have been simplified.
1866
- *
1867
- * The handler can use the values assigned to symbols and the assumptions
1868
- * about symbols, for example with `arg.numericValue`, `arg.isInteger` or
1869
- * `arg.isPositive`.
1870
- *
1871
- * Even though a symbol may not have a value, there may be some information
1872
- * about it reflected for example in `this.isZero` or `this.isPrime`.
1873
- *
1874
- * The handler should not perform approximate numeric calculations, such
1875
- * as calculations involving decimal numbers (non-integers). Making exact
1876
- * calculations on integers or rationals is OK.
1877
- *
1878
- * Do not reduce constants with a `holdUntil` attribute of `"N"`
1879
- * or `"evaluate"`.
1880
- *
1881
- * This handler should not have any side-effects: do not modify
1882
- * the environment of the `ComputeEngine` instance, do not perform I/O,
1883
- * do not do calculations that depend on random values.
1884
- *
1885
- * If no simplification can be performed due to the values, domains or
1886
- * assumptions about its arguments, for example, return `undefined`.
1887
- *
1888
- */
1889
- simplify?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined;
2202
+ canonical?: (ops: ReadonlyArray<BoxedExpression>, options: {
2203
+ engine: IComputeEngine;
2204
+ }) => BoxedExpression | null;
1890
2205
  /**
1891
2206
  * Evaluate a function expression.
1892
2207
  *
@@ -1895,70 +2210,46 @@ export type FunctionSignature = {
1895
2210
  *
1896
2211
  * It is not necessary to further simplify or evaluate the arguments.
1897
2212
  *
1898
- * If performing numerical calculations, if all the arguments are exact,
1899
- * return an exact expression. If any of the arguments is not exact, that is
1900
- * if it is a literal decimal (non-integer) number, return an approximation.
1901
- * In this case, the value may be the same as `expr.N()`.
2213
+ * If performing numerical calculations and `options.numericalApproximation`
2214
+ * is `false` return an exact numeric value, for example return a rational
2215
+ * number or a square root, rather than a floating point approximation.
2216
+ * Use `ce.number()` to create the numeric value.
1902
2217
  *
1903
- * When doing an exact calculation:
2218
+ * When `numericalApproximation` is `false`, return a floating point number:
1904
2219
  * - do not reduce rational numbers to decimal (floating point approximation)
1905
- * - do not down convert bignums to machine numbers
1906
2220
  * - do not reduce square roots of rational numbers
1907
- * - do not reduce constants with a `holdUntil` attribute of `"N"`
1908
2221
  *
1909
- * If the expression cannot be evaluated, due to the values, domains, or
2222
+ * If the expression cannot be evaluated, due to the values, types, or
1910
2223
  * assumptions about its arguments, for example, return `undefined` or
1911
2224
  * an `["Error"]` expression.
1912
2225
  */
1913
- evaluate?: SemiBoxedExpression | ((ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined);
1914
- /**
1915
- * Evaluate numerically a function expression.
1916
- *
1917
- * The arguments `args` have been simplified and evaluated, numerically
1918
- * if possible, except the arguments to which a `hold` apply.
1919
- *
1920
- * The arguments may be a combination of numbers, symbolic
1921
- * expressions and other expressions.
1922
- *
1923
- * Perform as many calculations as possible, and return the result.
1924
- *
1925
- * Return `undefined` if there isn't enough information to perform
1926
- * the evaluation, for example one of the arguments is a symbol with
1927
- * no value. If the handler returns `undefined`, symbolic evaluation of
1928
- * the expression will be returned instead to the caller.
1929
- *
1930
- * Return `NaN` if there is enough information to perform the
1931
- * evaluation, but a literal argument is out of range or
1932
- * not of the expected type.
1933
- *
1934
- * Use the value of `ce.numericMode` to determine how to perform
1935
- * the numeric evaluation.
1936
- *
1937
- * Note that regardless of the current value of `ce.numericMode`, the
1938
- * arguments may be boxed numbers representing machine numbers, bignum
1939
- * numbers, complex numbers, rationals or big rationals.
1940
- *
1941
- * If the numeric mode does not allow complex numbers (the
1942
- * `engine.numericMode` is not `"complex"` or `"auto"`) and the result of
1943
- * the evaluation would be a complex number, return `NaN` instead.
1944
- *
1945
- * If `ce.numericMode` is `"bignum"` or `"auto"` the evaluation should
1946
- * be done using bignums.
1947
- *
1948
- * Otherwise, `ce.numericMode` is `"machine", the evaluation should be
1949
- * performed using machine numbers.
1950
- *
1951
- * You may perform any necessary computations, including approximate
1952
- * calculations on floating point numbers.
1953
- *
1954
- */
1955
- N?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression | undefined;
2226
+ evaluate?: ((ops: ReadonlyArray<BoxedExpression>, options: EvaluateOptions & {
2227
+ engine: IComputeEngine;
2228
+ }) => BoxedExpression | undefined) | BoxedExpression;
1956
2229
  /** Dimensional analysis
1957
2230
  * @experimental
1958
2231
  */
1959
- evalDimension?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => BoxedExpression;
1960
- /** Return the sign of the function expression. */
1961
- sgn?: (ce: IComputeEngine, args: ReadonlyArray<BoxedExpression>) => -1 | 0 | 1 | undefined;
2232
+ evalDimension?: (args: ReadonlyArray<BoxedExpression>, options: EvaluateOptions & {
2233
+ engine: IComputeEngine;
2234
+ }) => BoxedExpression;
1962
2235
  /** Return a compiled (optimized) expression. */
1963
2236
  compile?: (expr: BoxedExpression) => CompiledExpression;
2237
+ collection?: Partial<CollectionHandlers>;
2238
+ };
2239
+ /**
2240
+ * @category Definitions
2241
+ *
2242
+ */
2243
+ export type BaseDefinition = {
2244
+ /** A short (about 1 line) description. May contain Markdown. */
2245
+ description?: string | string[];
2246
+ /** A URL pointing to more information about this symbol or operator. */
2247
+ url?: string;
2248
+ /**
2249
+ * A short string representing an entry in a wikibase.
2250
+ *
2251
+ * For example `Q167` is the [wikidata entry](https://www.wikidata.org/wiki/Q167)
2252
+ * for the `Pi` constant.
2253
+ */
2254
+ wikidata?: string;
1964
2255
  };