在Julia中,methods函数可用于检索函数的方法. julia f(::Int) = 0f (generic function with 1 method)julia f(::String) = ""f (generic function with 2 methods)julia methods(f)# 2 methods for generic function "f":f(::String) in Main a
julia> f(::Int) = 0 f (generic function with 1 method) julia> f(::String) = "" f (generic function with 2 methods) julia> methods(f) # 2 methods for generic function "f": f(::String) in Main at REPL[1]:1 f(::Int64) in Main at REPL[0]:1
宏也可以有多种方法.
julia> macro g(::Int) 0 end @g (macro with 1 method) julia> macro g(::String) "" end @g (macro with 2 methods) julia> @g 123 0 julia> @g "abc" ""
但是,方法函数似乎不适用于宏,因为Julia首先调用宏,因为它们不需要括号.
julia> methods(@g) ERROR: MethodError: no method matching @g() Closest candidates are: @g(::String) at REPL[2]:2 @g(::Int64) at REPL[1]:2
我尝试使用表达式来包含宏,但这不起作用.
julia> methods(:@g) # 0 methods for generic function "(::Expr)":
如何检索宏的方法?
我会在我的〜/ .juliarc.jl中的一个模块(MethodsMacro)中放入一个泛型宏(@methods)以及该行:使用MethodsMacro.通过这种方式,您可以在每个Julia会话中使用它,例如:julia> module MethodsMacro export @methods macro methods(arg::Expr) arg.head == :macrocall || error("expected macro name") name = arg.args[] |> Meta.quot :(methods(eval($name))) end macro methods(arg::Symbol) :(methods($arg)) |> esc end end MethodsMacro julia> using MethodsMacro julia> @methods @methods # 2 methods for macro "@methods": @methods(arg::Symbol) at REPL[48]:12 @methods(arg::Expr) at REPL[48]:6 julia> f() = :foo; f(x) = :bar f (generic function with 2 methods) julia> @methods f # 2 methods for generic function "f": f() at REPL[51]:1 f(x) at REPL[51]:1