2
$\begingroup$

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].
$\endgroup$
2
$\begingroup$

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]}

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – Jacob Jun 28 at 21:59
  • $\begingroup$ I have corrected the question adding cases with minus. $\endgroup$ – Jacob Jun 28 at 22:06
  • $\begingroup$ @Jacob What about (-1 - I) x + y + z? What kinds of summands will you have? $\endgroup$ – Carl Woll Jun 28 at 22:25
  • $\begingroup$ I have only sums or differences of varying number of variables. I do not have to consider general expressions. $\endgroup$ – Jacob Jun 28 at 23:00
  • $\begingroup$ @Jacob So, only f[x+y+z] gets converted, not f[x+y+z-u]? $\endgroup$ – Carl Woll Jun 28 at 23:08
0
$\begingroup$
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]}

$\endgroup$
0
$\begingroup$

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!

$\endgroup$
0
$\begingroup$
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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.