Why does constraining a Perl 6 named parameter to a definite value make it a required value?
All parameters always have some value, even if they're optional. I clarified the docs you reference in 379678 and b794a7.
Optional parameters have default default values that are the type object of the explicit or implicit type constraints (implicit constraint is Any
for for routines and Mu
for blocks).
sub (Int $a?, Num :$b) { say "\$a is ", $a; say "\$b is ", $b }()
# OUTPUT:
# $a is (Int)
# $b is (Num)
Above, the default default values pass the type constraint on the parameters. And the same is the case if you use the :U
or :_
type smileys.
However, when you use the :D
type smiley, the default default no longer matches the type constraint. If that was left unchecked, you'd lose the benefit of specifying the :D
constraint. As the default default type objects would, for example, cause an explosion in the body of this routine, that expects the parameters to be definite values.
sub (Int:D $a?, Num:D :$b) { say $a/$b }()
And to answer the titular question of whether specifying the :D
should make parameters required automatically. I'm -1 on the idea, as it introduces a special case users will have to learn just to save a single character of typing (the !
to mark param as required). Doing so also produces a less-helpful error that talks about arity or required parameters, rather than the actual problem: the default default of the parameters failing the typecheck on the parameter.
FWIW, a similar issue exists with optional positional parameters:
sub a(Int:D $number?) { ... }
a; # Parameter '$number' of routine 'a' must be an object instance of type 'Int', not a type object of type 'Int'. Did you forget a '.new'
The same problem occurs if you specify a type object as a default:
sub a(Int:D $number = Int) { ... };
a; # # Parameter '$number' of routine 'a' must be an object instance of type 'Int', not a type object of type 'Int'. Did you forget a '.new'
I'm afraid that's just a consequence of the :D
constraint when applied to parameters: you just must specify a defined default value for it to be callable without any parameters.
Another approach could of course be the use of a multi sub
and required named parameter:
multi sub a() { say "no foo named" }
multi sub a(Int:D :$foo!) { say "foo is an Int:D" }
Hope this helps
I solved this by checking for exactly the type Any
or smart matching for the one I actually want:
sub f ( :$f where { $^a.^name eq 'Any' or $^a ~~ Int:D } ) {
put $f.defined ?? "f defined ($f)" !! 'f not defined';
}
f( f => 5 );
f();
To answer my original question: all parameters are required. It's merely a matter of how they get values. It can be through an argument, an explicit default, or an implicit default (based from its type constraint).