mathjs
mathjs copied to clipboard
Support destructuring assignment
Some of the functions I am planning to implement will return more than one result, as example we have matrix LU decomposition. Syntax in other math programs (scilab) is like:
[L, U, P] = lu(A)
In this case the function will decompose the matrix A into three matrices that meet the condition:
A * P = L * U
Another case for the same function in scilab is:
[L, U] = lu(A)
Where:
A = L * U
Does the parser supports a syntax similar to the one above?
What should the function return in this case? Object with three fields or an array of Matrix?
The parser doesn't yet support this, but we definitely need something like this.
For the parser it makes sense to copy the syntax used by Matlab/Scilab, which is [L, U, P] = lu(A)
. We should think though what the underlying JavaScript function should return. ES6 will probably support destructuring of function results. You can destructure both arrays and objects. From a JavaScript point of view I would find it most logic to return an object {L: ..., U: ..., P: ...}
, as this makes the meaning of the returned results explicit.
What do you think?
I agree with returning an object. The implementation I am working on returns an object with the three fields.
For now we can provide some formatting to the object been returned so it will look nice on the cli. There are some functions I will later work on that accept the LUP decomposition as a parameter, something like:
x = lusolver(lup, b)
Makes sense. It's time to extend the parser: it will need this destructuring, and I still need to support for JSON objects.
Potentially related: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
It remains the case that the parser does not support
{L, U, P} = lup(M)
but that it might be nice if it did.
Yes definitely!
Oh, and I did not realize that #1542 was a proposed implementation of this for the Array/Matrix case (that seems to have run aground on some of the fine details of the specifics of notation and semantics of such a destructuring assignment).