I have a linear function which also follows the chain rule (it is a derivation), so I defined it recursively, following a Wolfram tutorial (which I've misplaced) and other related answers:
fn[f_+g_] := fn[f] + fn[g]
fn[f_ g_] := fn[f] g + f fn[g]
Unfortunately, I have to run this on polynomials with thousands of terms, which inevitably leads to
$RecursionLimit::reclim: Recursion depth of 1024 exceeded.
I get around the issue in certain specific cases by using Distribute
, which doesn't work well with the recursive chain rule. For example:
(* fn[f_+g_]:= fn[f]+fn[g]; *)
fn[f_ g_] := fn[f] g + f fn[g];
Distribute[fn[x (y + z)]]
(* Out[1]= (y + z) fn[x] + x fn[y + z] *)
I have also previously raised the $RecursionLimit
but I feel requiring my definition of fn
to work with infinitely many recursions is probably a bad idea (since I eventually run into larger and larger polynomials, I inevitably keep raising the recursion limit until I get tired of doing so and remove the limit altogether).
My question is: are there any problems with using
fn[f__Plus] := Plus @@ (fn /@ (List@@f))
as an alternative to the recursive rule? My question is a bit leading, but I do feel suspicious of the answer that Apply
is always preferable to the recursive definition.