保留嵌套命名参数的默认值

我怀疑这个问题很容易回答,答案是否定的。但是,我想确保我没有遗漏任何东西。

考虑以下代码:

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

有没有一种好方法可以更改&for的签名/正文,&g以便打印foo而不是Any

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

选项1:

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

选项 2:

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

这些都不是很好的方法,所以我希望有人可以向我展示一种我缺少的更优雅的方法。另一方面,这两个都可以工作,所以如果这只是一个稍微不优雅的角落(而且是一个非常小的角落),那肯定不会有什么大不了的。

回答

我会使用选项 1,或者如果 sub "g" 总是只调用 sub "f",来创建所有参数的捕获,然后传递它:

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

  • My guess has always been... `|c` in a parameter list binds the symbol `c` to a fresh capture built from the remaining part of the incoming capture that has not yet been removed by the signature processing prior to the `|c`. If the `|c` is right at the start of the signature, the compiler just binds to the original capture. Similarly, `|c` in an argument list does the logical inverse, notionally slipping the `c` capture into a new capture being constructed for the call, but, again, presumably just using the capture directly as is if there's nothing else in the argument list.

以上是保留嵌套命名参数的默认值的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>