How should I define functions that distribute over Plus?

3

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.

Eric

Posted 2015-03-25T08:18:04.847

Reputation: 33

If you are able to include code that generates an example polynomial that produces the recursion limit warning you may get better answers sooner, as it makes it less work to answer. – Mr.Wizard – 2015-03-25T08:44:49.157

Answers

2

Lacking an example of your polynomial I did not attempt to test this extensively, but try:

ClearAll[fn]

fn[p_Plus] := fn /@ p

fn[f_ g_] := fn[f] g + f fn[g]

Mr.Wizard

Posted 2015-03-25T08:18:04.847

Reputation: 259 163

1Here you are: x[] := Unique["x"]; poly = Times @@ Table[x[], {1024}] :) – Kuba – 2015-03-25T08:52:47.173

@Kuba That's multiplication. I thought this question was about the additive rule? – Mr.Wizard – 2015-03-25T09:00:38.823

Yes, probably you are right, OP didn't say how big those terms are really, you never know ;) – Kuba – 2015-03-25T09:03:51.940

@Kuba's example is fine and I'm having trouble getting a MWE representing my specific problem so I'm starting to suspect I hit the recursion limit more from the chain rule (how you hit the recursion limit depends on how the expression is expanded, right?) than from the additive rule. Anyways, using /@ works better than what I wrote above and I think I'll mark this as a solution. Thanks! – Eric – 2015-03-25T22:15:44.163