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

如何判断一个名称是否为仅本地可访问的函数?

如何检查一个名称是否为本地可访问且仅本地可访问的函数?

示例代码

function out = top_level_function(name)

% ???

    function helper2
    end
end

function helper1

end

期望输出

>> top_level_function('helper1')
>> ans =
     1
>> otherwise_valid_function(); % 可正常执行
>> top_level_function('otherwise_valid_function')
>> ans =
     0

原思路与疑问

一开始想到用 isa(eval(['@',name]),'function_handle') 搭配非文件、非内置函数的检查逻辑,这种方案在没有本地名称遮蔽的场景下可能生效,但有两个疑问待解决:

  • 这种方式会不会允许name作为表达式而非纯函数名被求值?
  • 遇到本地名称遮蔽的情况时该怎么处理?

最终实现代码

msg=['value of ',name,' must be a valid local function name.'];
isIn=false;
try
    if isStringScalar(name) % 基础输入类型检查占位代码
        varargin{1}=char(name);
    end
    isIn=~isempty(which(name,'in',mfilename));
    msg=[msg,' Received ''',name,'''.'];
catch ME
end
if isIn
    out=eval(['@',name,';']);
else
    if ~exist('ME','var') || isempty(ME)
        error(msg)
    else
        fprintf(2,['%s: %s',newline], ME.identifier, ME.message);
        error(msg);
    end
end

该实现可以让helper1、helper2以及top_level_function内部的其他辅助函数拥有自动外部调用与测试接口。

内容的提问来源于stack exchange,提问作者Argyll

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 07:42:43