# Finitely many repeated replacements

I'm looking for good practices to replace a given function recursively n times by itself with its arguments. The following example (for n=2) hopefully makes it clear:

f[a_] := d[a + b] - d[a - b]
g[a_] := f[a + b] - f[a - b]
h[a_] := g[a + b] - g[a - b]
h[a]
(*-d[a - 3 b] + 3 d[a - b] - 3 d[a + b] + d[a + 3 b]*)


I came up with

repl[func_] := func /. (d[x_] -> d[x + b] - d[x - b])
Nest[repl, d[a], 3]


which works ok (and doesn't look like total nonsense to me). But now I got curious, do you know of any immediate improvements or better methods to do this?

• Looks fine to me, if you don't want to define repl then ReplaceAll[d[x_] -> d[x + b] - d[x - b]] could be used as the first argument to Nest (or an anonymous function could also be used). – C. E. Mar 10 at 16:20
• @C.E. How would you define an anonymous function for this task. Unfortunately I can't make it work… – freddy90 Mar 10 at 17:46
• Use # /. d[x_] -> d[x + b] - d[x - b] & as the first argument. – C. E. Mar 10 at 17:51

You could use ReplaceRepeated with the option MaxIterations->3:

res = ReplaceRepeated[d[a], d[x_]->d[x+b]-d[x-b], MaxIterations->3]


ReplaceRepeated::rrlim: Exiting after d[a] scanned 3 times.

-d[a - 3 b] + d[a - b] - d[a + b] - 2 (-d[a - b] + d[a + b]) + d[a + 3 b]

h[a] == Expand[res]


True

The syntax coloring is odd, though, might be a buglet.

Asking for a "better" method you should probably give some metric what is meant by "better. Is it efficiency? Is it easiness of generalization? Anyhow, if you would stick to built-in function in hope that they are more efficient one of the options could be:

n = 3;
DifferenceDelta[d[a - n b], {a, n, 2 b}]


I hope it helps...

• Yes, DifferenceDelta[] is the right solution for that specific example, but I believe the OP only used it as a toy example, and wanted more general guidelines. – J. M. will be back soon Mar 10 at 16:33