MathGroup Archive 2003

[Date Index] [Thread Index] [Author Index]

Search the Archive

RE: dynamic programming inside a function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg40432] RE: [mg40409] dynamic programming inside a function
  • From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
  • Date: Sat, 5 Apr 2003 03:59:39 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

>-----Original Message-----
>From: Ken Sale [mailto:kesale at llnl.gov]
To: mathgroup at smc.vnet.net
>Sent: Friday, April 04, 2003 8:24 AM
>To: mathgroup at smc.vnet.net
>Subject: [mg40432] [mg40409] dynamic programming inside a function
>
>
>Hi MathGroup,
>
>I'm trying to figure out how to create a function that remembers its 
>values inside a function definition (I want the temporary function to 
>stay hidden in a package eventually.  I've tried the following
>
>test[f_, vars_List] :=
>   Module[{v, vPat},
>     Clear[temp];
>     vPat = Sequence @@ (Pattern[#, Blank[]] & /@ vars);
>     v = Sequence @@ vars;
>     temp[vPat] := temp[v] = f[v];
>     ]
>
>When I evaluate
>test[Sin, {x}]
>
>I find that the definition of temp isn't what I want
>
>?temp
>
>temp[x_] := temp[v$97] = Sin[v$97]
>
>What I'd like to get instead is
>
>temp[x_] := temp[x] = Sin[x]
>
>I've tried putting ReleaseHold around various parts of the assignment 
>but so far haven't found a way to do what I want.
>
>Any help will be appreciated.
>
>Thanks,
>Ken
>-- 
>Ken Sale
>Group Leader / Physicist
>Radiation Technology Group
>Lawrence Livermore National Laboratory
>(925) 423-0686
>

Ken,

the problem is that for SetDelayed the rhs isn't evaluated such the variable
v$97 prevailes. But we cannot just evaluate the rhs, dent Set would
disappear. Insted we have to introduce the evaluated variable

In[12]:=
test[f_, vars_List] := Module[{v, vPat}, Clear[temp];
    vPat = Sequence @@ (Pattern[#, Blank[]] & /@ vars);
    v = Sequence @@ vars;
    Unevaluated[temp[vPat] := temp[v] = f[v]] /. HoldPattern[v] -> v;]

In[28]:= test[ArcTan, {x, y}]

In[31]:= temp[4, 5]
Out[31]= ArcTan[5/4]

In[32]:= ?temp
Global`temp
temp[4, 5] = ArcTan[5/4]
temp[x_, y_] := temp[Sequence[x, y]] = 
                    ArcTan[Sequence[x, y]]



Or else:

In[34]:= Clear[temp]
In[35]:=
test[f_, vars_List] := Block[{}, With[
      {vPat = Sequence @@ (Pattern[#, Blank[]] & /@ vars),
        v = Sequence @@ vars},
      temp[vPat] := temp[v] = f[v]]]

and later put temp into the braces of Block.

I don't know what you finally want to achieve, but be cautious with the
variable names; you cannot (or should not refer to them within
Module/Block). Such you need only to specify the number of parameters, and
better generate the symbols anonymously within.

--
Hartmut Wolf



  • Prev by Date: How to solve this coupled recurrence eqation?
  • Next by Date: Mathematica Training
  • Previous by thread: Re: dynamic programming inside a function
  • Next by thread: Re: dynamic programming inside a function