develooper Front page | perl.perl6.users | Postings from June 2020

proto and multi

Thread Next
From:
Richard Hainsworth
Date:
June 29, 2020 17:29
Subject:
proto and multi
Message ID:
47a4722a-9b96-2d6b-34d4-87b477b8afbc@gmail.com
I have several multi methods.

All of them have the same first statement, then differ depending on the 
signature.

proto seems to be a way to factor out the common statement, and there is 
a phrase in the Documentation that * can affect the dispatch, viz:

"You can give the |proto| a function body, and place the |{*}| where you 
want the dispatch to be done. This can be useful when you have a "hole" 
in your routine that gives it different behavior depending on the 
arguments given:"

The docs give and example proto, but unfortunately, not how this works 
with other multi's.

So  I tried this:

class NewClass {
     has $.debug is rw = False;
     has $.value is rw = 'Initial value';

     proto method handle(|c ) {
         note "value is $.value" if $.debug;
         { * } }
     multi method handle(Str $s) {
         $.value = $s;
         say 'in string' }
     multi method handle(Positional @s) {
         $.value = @s[0];
         say 'in positional' }
}

my NewClass $x .= new;

$x.handle('hello world');
$x.handle(<hello world>);
$x.debug = True;
$x.handle('hello world');
$x.handle(<hello world>);

#raku test.raku
#value is Initial value
#value is Initial value

I am wondering how to use proto and {*}


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About