# Replacing function depending on the number of summed elements in its argument

I want to replace function

f[x+y+z]


by

g[t]


but I do not want to touch

f[x+y-z], f[x-y-z], f[x+y+z+u], f[x+y] or f[x].


## 4 Answers

Here is one possibility:

{f[x], f[x+y], f[x+y+z], f[x+y+z+u]} /. f[a_Plus?(Length[#]==3&)]->g[t]


{f[x], f[x + y], g[t], f[u + x + y + z]}

Addendum

With the revised criteria, you could use:

length3[a_Plus] := Length[a]==3 && !MemberQ[a, -_]


Then:

{f[x+y+z], f[x+y-z], f[x-y-z], f[x+y+z+u], f[x+y], f[x]} /. f[_?length3] -> g[t]


{g[t], f[x + y - z], f[x - y - z], f[u + x + y + z], f[x + y], f[x]}

• This replaces also f[x-y-z] by g[t] while I want only f[x+y+z]. I should write that minus makes a difference. – Jacob Jun 28 at 21:59
• I have corrected the question adding cases with minus. – Jacob Jun 28 at 22:06
• @Jacob What about (-1 - I) x + y + z? What kinds of summands will you have? – Carl Woll Jun 28 at 22:25
• I have only sums or differences of varying number of variables. I do not have to consider general expressions. – Jacob Jun 28 at 23:00
• @Jacob So, only f[x+y+z] gets converted, not f[x+y+z-u]? – Carl Woll Jun 28 at 23:08
fs = {f[x + y + z], f[x + y - z], f[x - y - z], f[x + y + z + u], f[x + y] , f[x]};
fs /. Thread[
Select[fs, (Length[#[[1]]] == 3 &&
Total[Map[Length, #[[1]] /. Plus -> List]] == 0) &] -> g[t]]


{g[t], f[x + y - z], f[x - y - z], f[u + x + y + z], f[x + y], f[x]}

In case you want the "additive degree" of the variables to be 3; i.e. number of + terms minus number of - terms, this is a quick and dirty solution.

degree[expr_Plus] := Replace[expr, _Symbol -> 1, {-1}]

{f[x+y+z], f[x+y-z], f[x-y-z], f[x+y+z+u], f[x+y], f[x], f[x+y+z+u-v]} /. f[expr_Plus] /; 3 == degree[expr] -> g[t] // Print

(* {g[t], f[x + y - z], f[x - y - z], f[u + x + y + z], f[x + y], f[x], g[t]} *)


Try it online!

expr = {f[x +  y + z], f[x + y - z], f[x + y + z + u], f[x + y], f[x], h[x + y + z]};

expr /.  f @ HoldPattern[_Symbol + _Symbol + _Symbol] -> g[t]


{g[t], f[x + y - z], f[u + x + y + z], f[x + y], f[x], h[x + y + z]}

Also

expr /.  f[a_Symbol + b_Symbol + _Symbol] -> g[t]


same result

and

expr /. f[_?(Last @ CoefficientArrays @ # == {1, 1, 1} &)] :> g[t]


same result