Does Perl6 support dependent types?

后端 未结 2 1165
南旧
南旧 2021-02-13 13:22

I was recently looking at the wikipedia page for dependent types, and I was wondering; does Perl 6 actually introduce dependent types? I can\'t seem to find a reliable source cl

2条回答
  •  感动是毒
    2021-02-13 14:10

    Arguably yes as subsets are types that may depend on arbitrary conditions. However, the type system would be classified as unsound as type invariants are not enforced.

    In particular, a variable's type constraint is only checked on assignment, so modifications to an object that make it drop from a subset will lead to a variable holding an object it should not be able to, eg

    subset OrderedList of List where [<=] @$_;
    
    my OrderedList $list = [1, 2, 3];
    $list[0] = 42;
    say $list ~~ OrderedList;
    

    You can use some meta-object wizardry to make the object system automatically check the type after any method call by boxing objects in transparent guard objects.

    A naive implementation could look like this:

    class GuardHOW {
        has $.obj;
        has $.guard;
        has %!cache =
            gist => sub (Mu \this) {
                this.DEFINITE
                    ?? $!obj.gist
                    !! "({ self.name(this) })";
            },
            UNBOX => sub (Mu $) { $!obj };
    
        method find_method(Mu $, $name) {
            %!cache{$name} //= sub (Mu $, |args) {
                POST $!obj ~~ $!guard;
                $!obj."$name"(|args);
            }
        }
    
        method name(Mu $) { "Guard[{ $!obj.^name }]" }
        method type_check(Mu $, $type) { $!obj ~~ $type }
    }
    
    sub guard($obj, $guard) {
        use nqp;
        PRE $obj ~~ $guard;
        nqp::create(nqp::newtype(GuardHOW.new(:$obj, :$guard), 'P6int'));
    }
    

    This will make the following fail:

    my $guarded-list = guard([1, 2, 3], OrderedList);
    $guarded-list[0] = 42;
    

提交回复
热议问题