确定为给定的函数调用调度哪个方法

Cam*_*nek 8 julia

考虑findfirst功能。我可以findfirst使用methods以下方法查看定义了哪些方法:

julia> methods(findfirst)
# 9 methods for generic function "findfirst":
[1] findfirst(A::Union{AbstractString, AbstractArray}) in Base at array.jl:1672
[2] findfirst(p::Union{Base.Fix2{typeof(==),T}, Base.Fix2{typeof(isequal),T}}, r::StepRange{T,S}) where {T, S} in Base at array.jl:1758
[3] findfirst(pred::Base.Fix2{#s66,#s65} where #s65<:Union{Int8, UInt8} where #s66<:Union{typeof(==), typeof(isequal)}, a::Union{Array{Int8,1}, Array{UInt8,1}}) in Base at strings/search.jl:22
[4] findfirst(testf::Function, A::Union{AbstractString, AbstractArray}) in Base at array.jl:1754
[5] findfirst(testf::Function, A) in Base at array.jl:1747
[6] findfirst(pattern::AbstractString, string::AbstractString) in Base at strings/search.jl:104
[7] findfirst(ch::AbstractChar, string::AbstractString) in Base at strings/search.jl:124
[8] findfirst(r::Regex, s::AbstractString) in Base at regex.jl:327
[9] findfirst(A) in Base at array.jl:1663
Run Code Online (Sandbox Code Playgroud)

现在假设我想弄清楚当我调用findfirst(iseven, 1:4). 我怎么做?

Cam*_*nek 9

您可以使用@which宏:

julia> @which findfirst(iseven, 1:4)
findfirst(testf::Function, A::Union{AbstractString, AbstractArray}) in Base at array.jl:1754
Run Code Online (Sandbox Code Playgroud)

另一个例子:

julia> @which length(1:7)
length(r::AbstractUnitRange{T}) where T<:Union{Int128, Int64} in Base at range.jl:542

julia> @which length("hello world")
length(s::String) in Base at strings/string.jl:259
Run Code Online (Sandbox Code Playgroud)

编辑:

正如@giordano 在评论中指出的那样,您可以使用

@less findfirst(iseven, 1:4)
Run Code Online (Sandbox Code Playgroud)

或者

@edit findfirst(iseven, 1:4)
Run Code Online (Sandbox Code Playgroud)

如果您想查看将被调度的方法的源代码。@less使用系统寻呼机显示源代码。@edit将在文本编辑器中打开包含方法源代码的文件。您可以通过设置JULIA_EDITOR 环境变量来控制打开哪个编辑器。例如,您可以通过调用将编辑器设置为vim

ENV["JULIA_EDITOR"] = "vim"
Run Code Online (Sandbox Code Playgroud)

无论是在 REPL 中还是在您的启动文件中,~/.julia/config/startup.jl. 或者,您可以添加export JULIA_EDITOR=vim到linux/macos 上的.bashrc.bash_profile文件。

  • 我还要提到姊妹宏“@less”和“@edit”;-) (3认同)