Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping default values for nested named parameters

I suspect that this question is very easy to answer, and that the answer is "no". However, I want to make sure I'm not missing something.

Consider the following code:

sub f(:$a = 'foo') { say $a }
sub g(:$a) { f :$a }
g();  # OUTPUT: «(Any)»

Is there a good way to change the signature/body of &f or &g so that this prints foo instead of Any?

I know of two ways to get &f to use the default value for $a, but neither of them are great.

Option 1:

sub f(:$a = 'foo') { say $a }
multi g(:$a) { f :$a }
multi g()    { f }
g();  # OUTPUT: «foo»

Option 2:

sub f(:$a = 'foo') { say $a }
sub g(:$a) { f |(:$a with $a) }
g();  # OUTPUT: «foo»

Neither of these feel like great approaches, so I'm hoping that someone can show me a more elegant approach that I'm missing. On the other hand, these both work, so it certainly won't be a big deal if this is just a slightly inelegant corner (and a very small one).

like image 382
codesections Avatar asked Mar 09 '21 22:03

codesections


1 Answers

I would use either option 1, or if sub "g" always just calls sub "f", to create a capture of all parameters, and just pass that on:

sub f(str :$a = 'foo') { say $a }
sub g(|c) { f |c }
g a => "bar";  # "bar"
g;             # "foo"
like image 139
Elizabeth Mattijsen Avatar answered Nov 19 '22 14:11

Elizabeth Mattijsen