Perl 6
SMOP Multi Sub Dispatch: Revision 7

Multi subs in Perl 6 support two features:

  • lexical variants of outer-or-global multi subs
  • variant disambiguation

What do they mean?

Lexical Variants

my multi foo (Foo $a) {...};
for 1..4 {
    my multi foo (Bar $a) {...};
    # foo(Bar) is visible here
}
# but not here

Variant Disambiguation

class A {};
class B is A {};
multi foo (A $a) { say 1 };
multi foo (B $a) { say 2 };
foo(A.new());
foo(B.new());

Most languages that support multi dispatch doesn't support this feature, this is usually seen as a compile-time error, since the two variant are ambiguous. But this is a very important feature to Perl 6, since that's how objects can overload most operators. Which means you need a disambiguation code to sort all the matching candidates.

How to make it work

The dispatching would implement the following steps:

  • manual traversal of the lexical scope searching for variants: This is not a simple lookup because we need the variant declared in an inner scope not to hide the declaration in an outer scope.
  • check if package CANDO this sub: sub dispatch is 'no strict', meaning that if the symbol is not found in the current lexical scope, it might be in the package.
  • grep all the variants for ACCEPTS
  • sort them according to a "pluggable disambiguation code"
  • invoke the topmost variant on the sorted list

API

module P6SubDispatch {
     only sub dispatch ($name, $lexpad, $package) {...}
}
role P6VariantDisambiguator {
     only sub sort (*@variants) {...}
}

Room for optimization

Each variant declaration could hold a cache of all the outer declarations already sorted, meaning that it would just consume the first element of the lazy return of grep. Of course runtime declarations would drop the cache entirely and it would need to be rebuilt.


Upload Files

Click "Browse" to find the file you want to upload. When you click "Upload file" your file will be uploaded and added to the list of attachments for this page.

Maximum file size: 50MB

 
 
 
File Name Author Date Uploaded Size

Save Page As

Enter a meaningful and distinctive title for your page.

Page Title:

Tip: You'll be able to find this page later by using the title you choose.

Page Already Exists

There is already a page named XXX. Would you like to:

Save with a different name:

Save the page with the name "XXX"

Append your text to the bottom of the existing page named: "XXX"

Upload Files

Click "Browse" to find the file you want to upload. When you click "Add file" this file will be added to the list of attachments for this page, and uploaded when you save the page.

 
 
 
Add Tags

Enter a tag and click "Add tag". The tag will be saved when you save the page.

Tag: 

Suggestions: