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]
(*-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?

  • 3
    $\begingroup$ 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). $\endgroup$ – C. E. Mar 10 at 16:20
  • $\begingroup$ @C.E. How would you define an anonymous function for this task. Unfortunately I can't make it work… $\endgroup$ – freddy90 Mar 10 at 17:46
  • 1
    $\begingroup$ Use # /. d[x_] -> d[x + b] - d[x - b] & as the first argument. $\endgroup$ – 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]

This agrees with your answer after expanding:

h[a] == Expand[res]


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...

  • 1
    $\begingroup$ 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. $\endgroup$ – J. M. will be back soon Mar 10 at 16:33

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.