Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a standalone Signature as a signature in Perl 6?

Tags:

signature

raku

I was playing around with a Perl 6 implementation of a command-line program that takes several switches. The signature to MAIN was quite involved and a bit messy. I wondered if there was a way to define the signature somewhere else and tell the subroutine what to use:

# possibly big and messy signature
my $sig;
BEGIN { $sig = :( Int $n, Int $m ) };

multi MAIN ( $sig ) {
    put "Got $n and $m";
    }

MAIN doesn't see the variables in the signature even though the signature is set before MAIN compiles:

===SORRY!=== Error while compiling /Users/brian/Desktop/signature.p6
Variable '$n' is not declared
at /Users/brian/Desktop/signature.p6:7

I figured this sort of thing might be handy for generating methods after compile time and selecting signatures based on various factors.

like image 501
brian d foy Avatar asked Jan 08 '17 09:01

brian d foy


1 Answers

Short answer: No

Long answer: Still no. And if you could, you'd run into all kinds of trouble, because there's only one variable $n in your example. If you use the signature multiple times (or use it only once, and recurse into the subroutine that you attached it to), each signature binding would overwrite the previous value in that variable, causing some spooky action at a distance. There simply isn't a mechanism to cloning the variables involved in a free-floating signature.

Workarounds like using a match-all signature in the actual routine, and then use that to bind the capture to the signature suffer from this same flaw, and are thus IMHO not worth the trouble.

Maybe in the far future, some very advanced Macro feature might allow you to transplant signatures, but I don't think that part of macro development is even on our roadmap right now.

Instead of reusing bare signatures, you should reuse (possibly anonymous) routines with a signature attached, and install them with the name you want, for example

sub f(Int $n, Int $m) {
    # do something sensible here with $n and $m
}
constant &MAIN = &f;
# reuse &f for more 
like image 173
moritz Avatar answered Oct 24 '22 10:10

moritz