本文介绍了保留嵌套命名参数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怀疑这个问题很容易回答,答案是否".但是,我想确保我没有丢失任何东西.

考虑以下代码:

  sub f(:$ a ='foo'){说$ a}子g(:$ a){f:$ a}G();#输出:«(任何)» 

是否有一种很好的方法来更改& f & g 的签名/正文,以便打印出 foo 而不是吗?

我知道有两种方法可以使& f 使用 $ a 的默认值,但这两种方法都不是很好.

选项1:

  sub f(:$ a ='foo'){说$ a}多g(:$ a){f:$ a}多g(){f}G();#输出:«foo» 

选项2:

  sub f(:$ a ='foo'){说$ a}sub g(:$ a){f |(:$ a和$ a)}G();#输出:«foo» 

这两种方法都不是伟大方法,因此我希望有人可以向我展示一种我所缺少的更优雅的方法.另一方面,这两种方法都起作用,因此,如果这只是一个微不足道的角落(也是很小的一个角落),那么当然不会有什么大不了的.

解决方案

我将使用选项1,或者使用sub"g"总是只调用子"f",以创建所有参数的捕获,然后将其传递给:

  sub f(str:$ a ='foo'){说$ a}子g(| c){f | c}g a =>"bar";#"bar"G;#" foo" 

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).

解决方案

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"

这篇关于保留嵌套命名参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 09:52