(from p6i)

Larry Wall wrote:
On Thu, Feb 02, 2006 at 07:12:08PM +0100, Leopold Toetsch wrote:
: >... Anyway,
: >the P6 model of "state" is more like a persistent lexical than like
: >C's static. : : Sorry for my dumb question - what's the difference then? (Besides that C : dosn't have closures ;)

That *is* the difference.
[...]

I was thinking about this discussion on p6i, and I started thinking that there's something between "my" and state: a "state" variable that is created/initialized on each invocation of a sub but only if it's not already in the dynamic scope (i.e. if its not a recursive call). A slightly silly example of its use (using "temp state" as the quantifier) would be:

  sub factorial(Int $x) {
      temp state Int $result = 1;
      $result *= $x;
      factorial $x-1 if $x > 2;
      return $result if want;
  }
  say factorial 6;

This code is essentially the same as any other recursive factorial function, except that it doesn't use call-stack semantics to maintain its state. (I know P6 will do tail recursion, but sometimes I find myself building complex args/return values to pass state from one iteration to the next.)

Equivalent code without this feature is:

  sub factorial(Int $x) {
      my Int $result = 1;
      my sub fact1(Int $x) {
         $result *= $x;
         fact1 $x-1 if $x > 2;
      }
      fact1 $x
      return $result;
  }

Dave.

Reply via email to