[Date Index] [Thread Index] [Author Index]
Re: Beginner question on local vars./scoping
In article <a8itjb$gco$1 at smc.vnet.net>, Mark Pilloff <mdp1REMOVETHIS at uclink4.berkeley.edu> wrote: > Hi, > > I've written a function of the sort: > > function := Do some stuff > > The situation is that the 'Do some stuff' depends upon various global vars. > but some of the 'stuff' yields the same result unless some of the global > vars have changed. I'd like to memoize the results and have some local vars > to function that will remember the value of the global vars when function > was last called and only recompute if necessary. Right now I have global > vars like lastValueOfVarSeen and lastResultOfStep2 but I'd prefer to make > them local to function but still permanent. > > 1. How can I do this? > 2. Is there a better / more standard way to achieve the goal described > above? > > Thanks for any help, > Mark Best way to do this is probably to write a package that has it's own stored values in it, i.e. in its namespace. e.g.: (* Define the Package PackageX (or whatever name you want). *) BeginPackage["packageX`"]; (* Interface to packageX. *) AFunction::usage = "AFunction[inputval_]"; (* End Interface. *) Begin["`Private`"]; (* PackageX parameters *) valholder = 0; (* The function itself *) AFunction[in_]:=Block[ If[in == valholder, Return[Null], (* Do nothing *) valholder=in; (* Set new value for check on later function call *) (* Do other things *) ]; ] (* End of Private. *) End; (* End of PackageX. *) EndPackage; (* Example usage *) aparameter=10; AFunction[aparamter]; (* Function is active *) AFunction[aparamter]; (* Nothing happens *) aparameter=22; AFunction[aparamter]; (* Function is active, again *) Hope that helps. -- -- Lou Pecora - My views are my own.