如何在Raku函数体内检测是否传入了命名参数
在Raku中检测命名参数是否被显式传入
问题背景
你编写了如下包含两个函数的Raku代码,其中第二个函数包含带默认值的命名参数:
sub func1($x,$y) { # do something } sub some_func($x, $y , :$vel = 1, :$acceleration = 1/$vel) { # if $vel and $acceleration both are not missing # call func1($x, $y) # else do something else }
该函数支持两种调用方式:
- 不传入命名参数(使用默认值):
some_func($x, $y); # vel和acceleration使用默认值 - 显式传入两个命名参数:
some_func($x, $y, vel => 2, acceleration => 5); # vel和acceleration为传入的值
需要在some_func函数体内检测vel和acceleration是否都被显式传入,而非使用默认值。
解决方案
在Raku中,可以通过特殊哈希%_来实现检测——这个哈希会存储所有调用时显式传入的命名参数及其对应值。我们只需检查%_中是否同时存在vel和acceleration这两个键即可:
sub some_func($x, $y , :$vel = 1, :$acceleration = 1/$vel) { if %_<vel>:exists and %_<acceleration>:exists { func1($x, $y); } else { # 执行其他逻辑 } }
说明
%_<vel>:exists用于判断vel是否被显式传入,无论传入的值是什么,只要调用时指定了该参数,这个表达式就会返回True;- 同理
%_<acceleration>:exists检测acceleration的传入状态; - 只有当两个参数都被显式传入时,才会执行
func1($x, $y),否则进入else分支执行其他逻辑。
内容的提问来源于stack exchange,提问作者Suman
相关产品推荐
相关产品推荐

