Reputation: 113
I'm interested in defining an abstract function f[x,y]
in Mathematica through its properties only.
For instance, I would like Mathematica to know and simplify using f[a+b,c] = f[a,c] + f[b,c]
, etc.
How should I define a function in this way?
Upvotes: 1
Views: 132
Reputation: 9425
A generalized approach:
ClearAll[f]
e : f[s : (_Plus | _Times | _Dot), b__] := Thread[Unevaluated@e, Head[s]]
Now
f[a + b, c]
f[a*b, c]
f[a.b, c]
returns
f[a, c] + f[b, c]
f[a, c] f[b, c]
f[a, c].f[b, c]
Shorter version:
ClearAll[f]
e : f[(s : Plus | Times | Dot)[__], b__] := Thread[Unevaluated@e, s]
Upvotes: 2
Reputation: 6999
This may get you started.
Clear[f];
SetAttributes[f, HoldFirst];
f[s_Plus, b__] := f[#, b] & /@ List @@ Hold[s][[1]] // Total
f[a + b + c, d, e]
f[a, d, e] + f[b, d, e] + f[c, d, e]
Upvotes: 2