How to create and export dynamic statements

I have several classes (and you need a few more) that look like this:

use Unit;

class Unit::Units::Ampere is Unit
{
  method TWEAK { with self {
    .si            = True;
                   #     m·  kg·   s·   A   ·K· mol·  cd
    .si-signature  = [   0,   0,   0,   1,   0,   0,   0 ];
    .singular-name = "ampere";
    .plural-name   = "ampere";
    .symbol        = "A";
  }}

  sub postfix:<A> ($value) returns Unit::Units::Ampere is looser(&prefix:<->) is export(:short) {
    return Unit::Units::Ampere.new( :$value );
  };

  sub postfix:<ampere> ($value) returns Unit::Units::Ampere is looser(&prefix:<->) is export(:long) {
    $value\A;
  };
}

I would like to be able to create and export custom statements dynamically at runtime. I know how to work with EXPORT, but how to create a postfix statement on the fly?

+4
source share
2 answers

In the end, I basically did this :

sub EXPORT
{
    return %(
        "postfix:<A>" => sub is looser(&prefix:<->) {
            #do something
          }
    );
}

which is troubling.

+3
source

For the first question, you can create dynamic subsystems by returning sub from another. To accept only a parameter Ampere(where the software version is "Ampere"), use type capture in the function signature:

sub make-combiner(Any:U ::Type $, &combine-logic) {
    return sub (Type $a, Type $b) {
        return combine-logic($a, $b);
    }
}

my &int-adder = make-combiner Int, {$^a + $^b};
say int-adder(1, 2);
my &list-adder = make-combiner List, {(|$^a, |$^b)};
say list-adder(<a b>, <c d>);
say list-adder(1, <c d>); # Constraint type check fails

, sub, sub, , "sub". (. .)

, : ? is export : https://docs.perl6.org/language/modules.html#is_export

, is export . , . , MyModule.pm6:

unit module MyModule;

sub make-combiner(Any:U ::Type $, &combine-logic) {
    anon sub combiner(Type $a, Type $b) {
        return combine-logic($a, $b);
    }
}

my Str $name = 'int';
my $type = Int;
my package EXPORT::DEFAULT {
    OUR::{"&{$name}-eater"} := make-combiner $type, {$^a + $^b};
}

Perl 6:

perl6 -I. -MMyModule -e "say int-eater(4, 3);"

, 7. , anon sub, "" . , .

, , postfix. , Precedence , . .

+1

Source: https://habr.com/ru/post/1688802/


All Articles