Is there a way to print the expression string after the scope substitutions?
var n = math.compile('x * 2');
n.eval({x:2}); // returns 4
// I WISH I could do this:
n.toString({x:2}); // returns '2 * 2'
Is there a way to print the expression string after the scope substitutions?
var n = math.compile('x * 2');
n.eval({x:2}); // returns 4
// I WISH I could do this:
n.toString({x:2}); // returns '2 * 2'
It is first necessary to understand the way that MathJS parses to Expression Trees, and the different types of nodes used. You can read more here in the docs.
Algebraic variables get parsed as SymbolNodes. These will need to be substituted for their values. The simplest way to do this would be to use the transform function, which is explained in the API further down the page given above.
transform(callback: function)
Recursively transform an expression tree via a transform function. Similar to Array.map, but recursively executed on all nodes in the expression tree. The callback function is a mapping function accepting a node, and returning a replacement for the node or the original node. Function callback is called as callback(node: Node, path: string, parent: Node) for every node in the tree, and must return a Node. Parameter path is a string containing a relative JSON Path.
The transform function will stop iterating when a node is replaced by the callback function, it will not iterate over replaced nodes.
For example, to replace all nodes of type SymbolNode having name ‘x’ with a ConstantNode with value 3:
const node = math.parse('x^2 + 5*x')
const transformed = node.transform(function (node, path, parent) {
if (node.isSymbolNode && node.name === 'x') {
return new math.expression.node.ConstantNode(3)
}
else {
return node
}
})
transformed.toString() // returns '3 ^ 2 + 5 * 3'