mathjs
mathjs copied to clipboard
Override operators with the scope just like functions
f(x,y) = (y==0) ? undefined : x%y; evaluate('mod(22,0)', {mod: f})\n evaluate('22 % 0', {mod: f})
yields
[undefined, 22]
.
That is an interesting case. What happens right now is that functions and constants can be provided by the scope
passed to math.evaluate
, but this will not have effect on operators. I.e. passing mod
or add
or so to scope
will not replace the operators %
and +
etc. It makes sense that they would.
Originally posted by @josdejong in https://github.com/josdejong/mathjs/issues/2617#issuecomment-1189953880
The purposeof this issue is to ~~discuss whether overriding mod
, add
, etc. in the scope should affect the outcome of infix operators like %
, +
, etc. (And if the conclusion is so,~~ serve as a marker that a PR to do this is needed.)
My vote is yes. My reasons:
- I think we should strive for the operators to be exactly syntactic sugar for the function calls (even though they are generally the preferred read/write syntax). Therefore, their behavior should be the same.
- Jos and I have discussed the possibility (in some issue or other, but sorry I couldn't find the reference) of collapsing FunctionNode and OperatorNode (with just a flag for whether it was written infix) into a single class. Overall, it seemed like a good idea. Obviously that will be facilitated by having the behavior be the same. :)
Yes, I agree. It makes a lot of sense. And I don't think there is a use case where you would not want the operators consistent with the corresponding functions.
So, let's go for it 👍 .