mathjs icon indicating copy to clipboard operation
mathjs copied to clipboard

Override operators with the scope just like functions

Open gwhitney opened this issue 1 year ago • 2 comments

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

gwhitney avatar Jul 20 '22 16:07 gwhitney

My vote is yes. My reasons:

  1. 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.
  2. 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. :)

gwhitney avatar Jul 20 '22 16:07 gwhitney

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

josdejong avatar Jul 21 '22 15:07 josdejong