Question: Persistent variable

I would like to implement a persistent variable inside a procedure. That is:

  1. A variable that is first initialized if it does not exist.
  2. Its value is kept over multiple call of the procedure where it is defined.

As an example, the following procedure counts the number of times it is called:

restart;
CountProc := proc () 
     global m; 
     if `not`(m::integer) then      
          m := 0;
     end if; 
     m := m+1; 
     return m;
end proc;

CountProc(); CountProc(); CountProc();
                               1
                               2
                               3

That’s almost what I need, except the variable "m" should be local instead of global. How to do that?

Please Wait...