I'm writing a script that requires a variable number of symbolic variables and am struggling to understand how to evaluate the resulting expressions
MWE:
(%i1) foo:makelist(f[i],i,3);
(foo) [f[1],f[2],f[3]]
(%i2) bar:lreduce("*",foo);
(bar) f[1]*f[2]*f[3]
(%i3) vals:[1,2,3];
(vals) [1,2,3]
(%i4)
ev(bar,foo:vals);
(%o4) f[1]*f[2]*f[3]
Here, I wanted to evaluate the product for f[1]:1
, f[2]:2
and f[3]:3
.
The following works:
ev(bar,lambda([L], for i thru length(L) do f[i]:L[i])(vals));
however, I thought there was likely a more direct / practical method; perhaps a different way of declaring symbolic variables, altogether?
CodePudding user response:
In this case, since the free variables are just subscripted f[1], f[2], f[3]
, you can assign a list to f
temporarily and then it will fish out the appropriate values:
(%i6) e: f[1]*f[2]*f[3];
(%o6) f f f
1 2 3
(%i7) ev(e, f = [1, 2, 3]);
(%o7) 6
(%i8) ev(e, f = [a, b, 7]);
(%o8) 7 a b
More generally, the most straightforward way to handle problems like this one is to form a list of equations and then substitute into the expression. E.g.:
(%i12) e: x*y*z;
(%o12) x y z
(%i13) l: map ("=", [x, y, z], [11, 22, 33]);
(%o13) [x = 11, y = 22, z = 33]
(%i14) subst (l, e);
(%o14) 7986