gpt4 book ai didi

methods - 如何检索 Julia 宏的方法?

转载 作者:行者123 更新时间:2023-12-04 15:40:21 26 4
gpt4 key购买 nike

在 Julia ,methods函数可用于检索函数的方法。

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"
""

但是, methods函数似乎不适用于宏,因为 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

我尝试使用 Expr包含宏的 session ,但这不起作用。
julia> methods(:@g)
# 0 methods for generic function "(::Expr)":

如何检索宏的方法?

最佳答案

我会在我的 @methods 中的模块 ( MethodsMacro ) 中放置一个通用宏 ( ~/.juliarc.jl )沿着这条线:using MethodsMacro .这样您就可以在每次 Julia session 中使用它,例如:

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

关于methods - 如何检索 Julia 宏的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43038872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com