从特定方法调用更通用的方法

我试图从特定的方法中调用通用方法,但不知道如何调用。

function fn(x)
  # generic
  ...
end

function fn(x :: String)
  # I want to call the generic version here
  val = fn(x)
  # do something with val and then return it
  ...
end

这可能吗?

解决方法是使用可从通用方法和特定方法调用的辅助函数。例如

function helper(x)
  # main work is here
  ...
end

function fn(x)
  # generic
  helper(x)
end

function fn(x :: String)
  val = helper(x)
  # now use the val to do something
  ...
end

如果不使用此类助手,有没有办法控制调度以选择要使用的特定方法?Julia 中是否有类似:before:after关键字以及call-next-method来自 lisp CLOS 的内容?

回答

您可以使用该invoke功能:

julia> function fn(x)
         @info "generic $x"
       end
fn (generic function with 1 method)

julia> function fn(x :: String)
         @info "before"
         invoke(fn, Tuple{Any}, x)
         @info "after"
       end
fn (generic function with 2 methods)

julia> fn(10)
[ Info: generic 10

julia> fn("10")
[ Info: before
[ Info: generic 10
[ Info: after

(只是要清楚 - 打印"before""after"只是为了突出显示以什么顺序执行的内容 - 这里唯一与方法调度相关的是invoke函数)


以上是从特定方法调用更通用的方法的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>