这些方法在 Julia 中是如何工作的?

How does the methods function work in Julia?

methods function returns the method table of a function as also mentioned 。我正在寻找有关该功能如何工作的解释。

考虑 Julia 1.7 中的以下示例:

julia> f(a::Int64,b::Int64=1,c::Float64=1.0) = (a+b+c)
f (generic function with 3 methods)

julia> g(a::Int64,b::Int64=1;c::Float64=1.0) = (a+b+c)
g (generic function with 2 methods)

julia> methods(f)
# 3 methods for generic function "f":
[1] f(a::Int64) in Main at REPL[1]:1
[2] f(a::Int64, b::Int64) in Main at REPL[1]:1
[3] f(a::Int64, b::Int64, c::Float64) in Main at REPL[1]:1

julia> methods(g)
# 2 methods for generic function "g":
[1] g(a::Int64) in Main at REPL[1]:1
[2] g(a::Int64, b::Int64; c) in Main at REPL[1]:1

julia> f(1,1.0)
ERROR: MethodError: no method matching f(::Int64, ::Float64)
Closest candidates are:
  f(::Int64) at REPL[1]:1
  f(::Int64, ::Int64) at REPL[1]:1
  f(::Int64, ::Int64, ::Float64) at REPL[1]:1
Stacktrace:
 [1] top-level scope
   @ REPL[4]:1

julia> g(1,c=1.0)
3.0

julia>

我不太清楚为什么没有方法 f(::Int64, ::Float64)(因此出现错误)。我也想知道为什么 g(1,c=1.0) 没有错误,因为 g(::Int64, ::Float64)g(::Int64, c) 没有被列为 g.

的有效方法

啊,所以从技术上讲,这实际上是一个关于类型注释、分派、可选参数和关键字参数在 Julia 中如何工作的问题; methods 函数只是让您对该过程有一些了解,但做出这些决定的并不是 methods 函数。回答您的个人问题

It is not quite clear to me why there is no method f(::Int64, ::Float64) (hence the error).

没有方法,因为您只能从最后一个普通 (non-keyword) 参数连续地省略可选的普通 (non-keyword) 参数。考虑以下情况:

julia> f(a=1, b=1, c=1, d=1) = a + 2b +3c +4d
f (generic function with 8 methods)

julia> f(2,4)

如果没有这方面的规则,编译器将不知道所提供的 24 是否应该用于 ab ,或者我的意思是实际上我希望 2 转到 a4 转到 d?或 c?或者任何东西!这将是无法确定的。所以我们有一个规则,规则是第一个参数到a,第二个到b,省略的是cd。即使指定了默认值,也不能省略中间参数,只能省略最后 N 个可选参数。这只是规则,你有没有应用类型注解都没有关系。

I am also wondering why there is no error for g(1,c=1.0) given that g(::Int64, ::Float64) or g(::Int64, c) are not listed as valid methods for g.

首先,g(::Int64, ::Float64)g(::Int64, c) 没有方法,因为关键字参数(在本例中,c)不参与调度。 g(1,c=1.0) 没有错误,因为当你写 g(1,c=1.0) 时,b 的可选参数正在回落到它的默认值,所以你实际上是在调用 g(1,1,c=1.0) 当你写g(1,c=1.0),您已明确指定将 1.0 分配给 c,因此它不可能是 b 的值。 b 的值必须回退到默认值 1