繁体   English   中英

如何指定类型签名以在 Julia 中使用 InteractiveUtils.edit 查找特定方法?

[英]How to specify the type signature to find a specific method with InteractiveUtils.edit in Julia?

为了快速找到一些方法的实现,我想使用InteractiveUtils.edit

例如,如果我想查看methodswith的实现,我应该能够编写类似edit(methodswith) 但是,由于methodswith函数有多种方法,我得到:

ERROR: function has multiple methods; please specify a type signature

如何指定类型签名? 我知道我可以找出带有methods(methodswith) ,并给出如下签名:

[1] methodswith(t::Type; supertypes) in InteractiveUtils at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.0/InteractiveUtils/src/InteractiveUtils.jl:169

如何将其插入到edit调用中?

我知道有@edit可以与一些示例性函数调用一起使用。 但是,有时仅指定类型会更直接,因为为方法的示例调用构造对象还涉及对有效构造函数的一些调查。

特尔;博士:

如何在 Julia 中使用InteractiveUtils.edit查找函数的特定方法?

只需将参数类型作为第二个位置参数中的元组传递给edit

例如, edit(sin, (Int,))将为您打开sin的定义,该定义与Int类型的一个参数一起使用。

请注意,如果您想从 stdlib 编辑函数,这可能会失败(对于来自 Base 或非标准库的函数, edit将正常工作)。

在这种情况下,您必须使用methods函数并手动定位文件。 例如:

julia> using Statistics

julia> edit(mean, (Vector{Int},)) # this might not work as expected

julia> methods(mean, (Vector{Int},))
# 1 method for generic function "mean":
[1] mean(A::AbstractArray; dims) in Statistics at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.1\Statistics\src\Statistics.jl:132

现在你有了方法所在的文件名和行号,但是路径可能不对,所以你必须自己在Julia安装文件夹中找到文件。

以下是如何以编程方式检索此信息(假设您已正确指定了args并且只有一种方法匹配)。 首先定义一个函数:

function edit_stdlib(fun, args)
    m = methods(fun, args)
    @assert length(m.ms) == 1 # assume we have an exact match
    p = joinpath(Sys.STDLIB, splitpath(string(m.ms[1].file))[end-2:end]...)
    l = m.ms[1].line
    edit(p, l)
end

现在你可以编写例如edit_stdlib(mean, (Vector{Int},))来得到你想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM