When I enter the following:
Clear["Global`*"]
Func[f_, xx_] := Sum[D[f, xx[[s]]], {s, 1, 2}]
Func[x^2 + y^2, {x, y}]
Func[x^2 + s^2, {x, s}]
The first function evaluation works fine. The second gives the error "General: 2 is not a variable". The following expression appears in the stack trace, which makes it pretty clear why this happens:
$$ \sum_{s=1}^2 \partial_{(x,s)[[s]]} (s^2 + x^2) $$
The input variable $s$ is colliding with the sum index $s$.
It's pretty clear that I could avoid this by either
- Using very obscure index names so I'm unlikely to ever use then when calling the function later.
- Use normal index names but then take care to avoid using these as variables later on.
Neither of these seems ideal. Is there any way to "isolate" the sum index so that it won't collide with the input variables?
s
usingModule
.Func[f_, xx_] := Module[{s}, Sum[D[f, xx[[s]]], {s, 1, 2}]]
$\endgroup$Table
andSum
can be found in Do Table iteration variables need to be localized using Module?. $\endgroup$