Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the second colon in "List:D:" mean in Perl 6?

Tags:

raku

In the doc.perl6.org, i've seen many methods like this:

method sum(List:D: --> Numeric:D)

I konw List:D is a type of List that is defined, but what does the colon after the D mean (i.e. the second one in List:D:)?

I found some explain in S12-objects:

=head2 Invocants

Declaration of the invocant is optional. You may always access the current invocant using the keyword self. ... To mark an explicit invocant, just put a colon after it:

method doit ($x: $a, $b, $c) { ... }

but I don't understand, it's somewhat strange at first glance.

like image 492
chenyf Avatar asked Aug 21 '17 16:08

chenyf


2 Answers

By default methods have an invocant of self

So both of these would be equivalent:

method foo (        $a ){…}
method foo ( \self: $a ){…} # generates warning

So expanding the first example out to what it is sort-of short for

method sum( List:D \self: --> Numeric:D ){…} # generates warning

Basically you write it that way if you want to specify the type of the invocant (first argument) to a method, but just want to use self rather than specify a new variable.


The reason it uses the : to split up the invocant from the rest of the parameters is to simplify the common case where you don't specify the invocant, or type of the invocant.

like image 164
Brad Gilbert Avatar answered Nov 15 '22 09:11

Brad Gilbert


When you define a sub with a basic type constraint like this:

sub testB (Str $b) { say $b; }

then you can call it with an actual instance of the type in question as well as with the type object itself:

> testB("woo")
woo
> testB(Str)
(Str)

The :D is an additional type constraint, so you can only pass a "defined" instance:

sub testC (Str:D $c) { say $c; }
> testB(Str)
(Str)
> testC("hoo")
hoo
> testC(Str)
Parameter '$c' of routine 'testC' must be an object instance of type 'Str', not a type object of type 'Str'.  Did you forget a '.new'?
  in sub testC at <unknown file> line 1
  in block <unit> at <unknown file> line 1

More details can be found here

like image 43
Robert Lemmen Avatar answered Nov 15 '22 11:11

Robert Lemmen