Problem with recursive relations

I have problems with the following code:

ClearAll["Global*"]
SetAttributes[R, HoldAll]
SetAttributes[P, HoldAll]

Q[r_, f_, s0_] := Q[r, f, s0] = F[r, s0] D[f[s0], s0]

R[r_, f_[q_, g_, s0_], s0_] := F[r, s0] (r R[r - 1, f[q, g, s0], s0] + P[r - 1, f[q, g, s0], s0])
P[r_, f_[q_, g_, s0_], s0_] := F[r, s0] (r R[r - 1, f[q, g, s0], s0] - P[r - 1, f[q, g, s0], s0])
R[1, f_[q_, g_, s0_], s0_] := D[f[q, g, s0], s0]
P[1, f_[q_, g_, s0_], s0_] := 0


where functions R and P are defined via recursive relationship.

When I'm calling the following command:

R[1, Q[1, f, s0], s0]


I'm obtaining correct answer. However, when I'm calling the following:

R[2, Q[1, f, s0], s0]


it gives me an error of \$RecursionLimit.

Could you help me please with fixing this problem? I will appreciate any help!

You need to provide a condition to stop the recursion. I removed your R[1,...] and P[1,...] lines and used an If in the definition of R and P:

Q[r_, f_, s0_] := Q[r, f, s0] = F[r, s0] D[f[s0], s0]

R[r_, f_[q_, g_, s0_], s0_] :=
If[r > 1,
F[r, s0] (r R[r - 1, f[q, g, s0], s0] + P[r - 1, f[q, g, s0], s0]), D[f[q, g, s0], s0]]
P[r_, f_[q_, g_, s0_], s0_] :=
If[r > 1,
F[r, s0] (r R[r - 1, f[q, g, s0], s0] - P[r - 1, f[q, g, s0], s0]), 0]
`
• It works! Thank you very much for your help! May 31, 2020 at 19:34