You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:00:07