Suppose I have a simple function that I assign to an operator
f[a_, b_] := a + b
CirclePlus = f
Then I want to write
1 (+) 2 (+) 3
But it doesn't work, because it's trying to evaluate f[1,2,3]
.
So how does one instruct Mathematica that it should instead evaluate f[f[1,2],3]
, or alternatively how does one work with infix operators? I'd be okay if I had to write my as f[a_List]
instead, and then took care of things myself ...
-- Edit:
As the answer was deleted, note that making the function Flat
is not the answer, here, as far as I can see.
-- Edit:
Here is an exact copy of the MMA file to reproduce this problem
In[13]:= f[a_,b_]:=a+b;
f[a_,b_,c_]:=f[f[a,b],c]
CirclePlus=f;
1\[CirclePlus]2\[CirclePlus]5\[CirclePlus]6
Out[16]= f[1,2,5,6]
Answer
You can tell it by making a definition what it should do if you have more then 2 arguments:
ClearAll[f];
f[a_, b_, c__] := f[f[a, b], c];
CirclePlus = f
Then you get
And of course you have to add the definition of f
when it is called as binary function. So for instance, and only for the purpose of showing what happens:
f[a_, b_] := Row[{"(", a, "\[CirclePlus]", b, ")"}]
Here is how it looks when you use more than 3 terms. Note that the pattern is recursively applied until there are only 2 arguments in each call:
Comments
Post a Comment