问题
I want to write an (somehow) enhanced sum function which takes a number of indices at once, but I cannot understand how to get it work. Here is what I currently have:
(%i1) nsum(indexes, expr) :=
if indexes = []
then expr
else nsum(rest(indexes), sum(expr, first(indexes),1, N)) $
(%i2) nsum([i,j], i+j), nouns;
sum: index must be a symbol; found intosym(first(indexes))
#0: nsum(indexes=[k,j],expr=k+j)
I think this could be fixed by forcing Maxima expand first(indexes)
into a symbol before passing to sum
function. I tried ''(...)
and ev(..., nouns)
, but without any success.
回答1:
After some reading and trying I came to the following solution which uses apply
function to pre-evaluate arguments for sum
:
nsum(indexes, expr) :=
if indexes = []
then expr
else nsum(rest(indexes), apply(sum, ['expr, indexes[1], 1, N])) $
UPD1:
Unfortunately, there is something wrong with the above code, as it works well only for relatively simple expressions. In my case the straightforward approach works fine where nsum
fails:
(%i1) rot[i](f) := sum(sum(sum(sum(
G[r,i]*G[q,j]*w[i,j,k]*('diff(f[k], y[q]) + sum(K[k,q,m]*f[m], m, 1, N)),
r, 1, N),
j, 1, N),
k, 1, N),
q, 1, N) $
(%i2) rot2[i](f) := nsum( [r,j,k,q],
G[r,i]*G[q,j]*w[i,j,k]*('diff(f['k], y[q]) + sum(K[k,q,m]*f[m], m, 1, N))) $
(%i3) rot[1](f);
(%o3) ... Yelds the result.
(%i4) rot2[1](f);
apply: subscript must be an integer; found: k
lambda([i,j],diff(ys[i],x[j]))(i=k,j=1)
UPD2:
The code works indeed. It was 'k
accidentally left in rot2
definition instead of just k
.
来源:https://stackoverflow.com/questions/31566284/force-evaluate-index-expression-before-passing-to-sum