# How to match a pattern only when it is not used as a head?

I am working on modifying a mathematical expression and need some assistance. I have the following equation:

-27 f + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n


I aim to replace occurrences of f with f[n], but I want to apply this transformation selectively. Specifically, I aim to replace f only where it does not serve as a function head. That means I want to transform standalone instances of f into f[n] without altering f when it's followed by square brackets and arguments (like f[1 + n], f[2 + n], etc.).

Is there a method or function in Mathematica to help me achieve this selective replacement?

expr = -27 f + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n;

p = Position[expr, f, Heads -> False]


{{1, 1, 2}}

MapAt[f[n] &, expr, p]


-27 f[n] + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n

This trick is often useful with ReplaceAll: if you want some things to remain unaffected, you add a trivial replacement rule for that case before the replacement rule you really want

-27  f + 27  f[1 + n] - 9  f[2 + n] + f[3 + n] == 1 + 3  n /. {
expr : _f :> expr,
f -> f[n]
}


-27 f[n] + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n

• What does _f do here? Commented Feb 20 at 9:48
• @faceclean _f is a pattern that matches expressions like f[1 + n] where f is the head. Commented Feb 20 at 9:56
expr = -27 f + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n

expr /. f[a__] :> g[a] /. f -> f[n] /. g[a__] :> f[a]


Result:

-27 f[n] + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n

expr = -27  f + 27  f[1 + n] - 9  f[2 + n] + f[3 + n] == 1 + 3  n;


Another way using Cases:

vars = Union@Cases[#, s1_@s2_ | s3_Symbol, Depth@#] &@expr;

rules = # -> If[# === f, #[n], #] & /@ # &@vars;

expr /. rules

(*-27 f[n] + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n*)