MathGroup Archive 2002

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

Search the Archive

Re: Beginner question on local vars./scoping

  • To: mathgroup at smc.vnet.net
  • Subject: [mg33681] Re: Beginner question on local vars./scoping
  • From: "Louis M. Pecora" <pecora at anvil.nrl.navy.mil>
  • Date: Sat, 6 Apr 2002 00:48:59 -0500 (EST)
  • Organization: Naval Research Laboratory, Washington, DC
  • References: <a8itjb$gco$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

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.


  • Prev by Date: Re: Unexpected brainmalfunction [was: Unexpected result with RSolve?]
  • Next by Date: Re: binomial distribution
  • Previous by thread: Beginner question on local vars./scoping
  • Next by thread: RE: Beginner question on local vars./scoping