3

Constraints are apparently not used to select one in a multi

multi sub cuenta( Str $str ) { say $str };
multi sub cuenta( $file where .IO.e ) { say $file.IO.slurp };
cuenta( $*PROGRAM-NAME ); # Outputs the file name

That means it's using the first multi, not the second. However, this works as intended:

subset real-files of Str where .IO.e;
multi sub cuenta( Str $str ) { say $str };
multi sub cuenta( real-files $file ) { say $file.IO.slurp };
cuenta( $*PROGRAM-NAME );

printing the content of the program itself. This probably says something about type checking and multi scheduling, but I'm not sure if it's by design or it's just a quirk. Any idea?

jjmerelo
  • 22,578
  • 8
  • 40
  • 86

1 Answers1

7
multi sub cuenta( Str $str ) { say $str };
multi sub cuenta( Str $file where .IO.e ) { say $file.IO.slurp };
                # ^^^
cuenta( $*PROGRAM-NAME ); # Outputs the file

subset real-files        where .IO.e;
                # ^^^^^^
multi sub cuenta( Str $str ) { say $str };
multi sub cuenta( real-files $file ) { say $file.IO.slurp };
cuenta( $*PROGRAM-NAME ); # Outputs the file name

The base type of a parameter is checked first to establish candidates. Only the narrowest matching multis are candidates for dispatch. A where constraint only applies if there are multiple matching candidates with the same base type. If not specified, the base type of a parameter or a subset is Any.

This is by design.

raiph
  • 31,607
  • 3
  • 62
  • 111