Re: Setting up dummy variables
- To: mathgroup at smc.vnet.net
- Subject: [mg35879] Re: [mg35813] Setting up dummy variables
- From: "Johannes Ludsteck" <johannes.ludsteck at wiwi.uni-regensburg.de>
- Date: Mon, 5 Aug 2002 06:01:48 -0400 (EDT)
- Organization: Universitaet Regensburg
- Sender: owner-wri-mathgroup at wolfram.com
Dear Chrisopher,
here is a simple rough and dirty way to set up functions
that use dummy variables. As an example, I set up
functions which simulate Sum[...].
The simplest, but inefficient strategy is to use
substitution:
sumsim0[f_,{dum_Symbol,lo_Integer,up_Integer}]:=
Block[{i},Plus@@Table[f/.dum->i,{i,lo,up}]]
Evaluation can be increased considerably, if you generate
a local Function object using Evaluate, since then the
slow pattern substitution can be avoided:
sumsim[f_,{dum_Symbol,lo_Integer,up_Integer}]:=
Block[{i,ff},
ff=Function[{i},Evaluate[f/.dum->i]];
Plus@@Table[ff[i],{i,lo,up}]]
Example:
sumsim[f[a,{b,c},d],{a,0,2}]
returns
f[0,{b,c},d]+f[1,{b,c},d]+f[2,{b,c},d]
This is only a rough and dirty implemenation, since it
does not account for how f is defined.
For example, if the definition of f were
f[a,b_]:=(a+b)^2
sumsim[f[a,b],{a,0,2}]
would replace 'a' subsequently by 0,1,2 and produce
b^2 + (1+b)^2 + (2+b)^2, which is not correct, since
there appears no Blank (_) after a in the definition of f
and f should be returned unevaluated if its firs argument
is not 'a'. You could account for this by using the tests
in the following version more sophisticated of the program:
SetAttributes[sumsim,HoldFirst]
sumsim[f_,{dum_Symbol,lo_Integer,up_Integer}]:=
Module[{i,ff,argli=Apply[List,Unevaluated[f]],
h=Head[Unevaluated[f]]},
If[TrueQ[Apply[h,argli/.dum->i]==f],
ff=Function[{i},Evaluate[f/.dum->i]];
Plus@@Table[ff[i],{i,lo,up}],
Plus@@Table[Apply[h,argli/.dum->i],{i,lo,up}]]]
Best regards,
Johannes
Best regards,
Johannes
On 2 Aug 2002, at 2:41, Christopher Maierle wrote:
> Hi all,
>
> How do I set up a function that behaves like the Mathematica function Sum vis-a-vis
> its treatment of dummy variables? For example I can define i=6 and then
> enter
>
> Sum[f[i],{i,1,n}]
>
> and mathematica will not make the substitution i->6 even though the output
> generally still involves the dummy variable i. I figure this has something
> to do with Modules, Blocks, and Holds but I'm not sure how to put it all
> together. Any help would be greatly appreciated.
>
> -chris
>
<><><><><><><><><><><><><><><><><><>
Johannes Ludsteck
Institut fuer Volkswirtschaftslehre
Lehrstuhl Prof. Dr. Moeller
Universitaet Regensburg
Universitaetsstrasse 31
93053 Regensburg
Tel +49/0941/943-2741