codesections
codesections

Reputation: 9600

Can I copy a function with its *current* state?

Raku's state declarator can be used to give a subroutine or other block its own local state that persists across multiple invocations of the function:

sub f { state $n++ }
say f; # OUTPUT: «0»
say f; # OUTPUT: «1»
say f; # OUTPUT: «2»

I'm aware of two ways to "copy" a function that has internal state: First, I can assign it to a new &-sigiled variable with code like my &f1 = &f. This results in &f1 effectively being an alias to &f and means that they share state – anything that alters the state of &f or &f1 will also change the other function's state.

Second, I can make a clone of &f with code like my &f2 = &f.clone. This will create an independent function with state that is initialized to any default values in &f (that is, with $n being Any for the code above).

However, I'm hopping for a third way to copy &f that (like option 1) would preserve the current value of &f's state but that (like option 2) would make that state independent from &f's. In other words, I'd like to be able to use the commented-out lines below:

sub f { state $n++ }
say f; # OUTPUT: «0»
say f; # OUTPUT: «1»
say f; # OUTPUT: «2»
my &f1 = &f;
my &f2 = &f.clone;
# my &f3 = ???;
say f; # OUTPUT: «3»
say f; # OUTPUT: «4»
say f1; # OUTPUT: «5»
say f2; # OUTPUT: «0»
# say f3; # (desired) OUTPUT: «3»

Is there any way to save &f's state like that (maybe with something fancy with wrap or similar that I can't think of)? Or am I just asking to do something that isn't currently possible?

Upvotes: 8

Views: 114

Answers (1)

Jonathan Worthington
Jonathan Worthington

Reputation: 29454

No, there's not a way - not even if one were willing to write a module that depends on unsupported Rakudo internals.

State variables are currently handled all the way down in the runtime (typically, MoarVM), where they are attached to a bytecode handle. Cloning a Block in turn clones the underlying bytecode handle, which explicitly does not clone the state variables.

Upvotes: 6

Related Questions