完全使用关键字参数的函数的多重派发

考虑函数f1f2,其中

  • f1完全使用关键字参数,
  • f2完全不使用关键字参数

初次之外都相同,都定义两种methods

function f1(;a,b)
    a
end
function f1(;c,d,e)
    e
end

function f2(a,b)
    a
end
function f2(c,d,e)
    e
end

结果

f1 (generic function with 1 methods)
f2 (generic function with 2 methods)

很明显f2根据参数数目定义出了2种methodsf1却没有,为什么?

Methods · The Julia Language

Keyword arguments behave quite differently from ordinary positional arguments. In particular, they do not participate in method dispatch. Methods are dispatched based only on positional arguments, with keyword arguments processed after the matching method is identified.

2 个赞

Methods · The Julia Language
Keyword arguments behave quite differently from ordinary positional arguments. In particular, they do not participate in method dispatch. Methods are dispatched based only on positional arguments, with keyword arguments processed after the matching method is identified.

根据楼上大佬给的文档,看来函数的关键字参数部分是不参与多重派发的。Julia内使用函数的多重派发还是要老老实实使用 positional arguments,而不是 keyword arguments

julia> f1(a = 1, c = 2) = a + 2c
f1 (generic function with 3 methods)

julia> f1(a = 1, b = 2) = a + 3b
f1 (generic function with 3 methods)

julia> f2( a; b = 1) = a + b
f2 (generic function with 1 method)

julia> f2( a; c = 1) = a + 2c
f2 (generic function with 1 method)

julia> f2( a; b = 1, c = 1) = a + b + 2c
f2 (generic function with 1 method)

julia> f3( a; b = 1) = a + b
f3 (generic function with 1 method)

julia> f3( a, b; c = 1) = a + b + 2c
f3 (generic function with 2 methods)

help?> f1
search: f1 Inf16 ComplexF16 fld1 Float16 fldmod1

  No documentation found.

  f1 is a Function.

  # 3 methods for generic function "f1":
  [1] f1() in Main at REPL[2]:1
  [2] f1(a) in Main at REPL[2]:1
  [3] f1(a, b) in Main at REPL[2]:1

help?> f3
search: f3 Inf32 ComplexF32 Float32

  No documentation found.

  f3 is a Function.

  # 2 methods for generic function "f3":
  [1] f3(a; b) in Main at REPL[6]:1
  [2] f3(a, b; c) in Main at REPL[7]:1
4 个赞

关键词参数不参与多重分派。