在Julia中,如何在单独的模块中提供方法的默认实现?例如,如果抽象类型位于相同的模块中,我就没有问题,这就像我期望的那样工作:
abstract type Foo end
howdy(x::Foo)::Union{String, Nothing} = nothing
struct Bar <: Foo end
function howdy(x::Bar)::Union{String, Nothing}
"I'm a Bar!"
end
struct Baz <: Foo end
if abspath(PROGRAM_FILE) == @__FILE__
bar = Bar()
s = howdy(bar)
if isa(s, String)
println(s)
end
baz = Baz()
t = howdy(baz)
if isa(t, String)
println(t)
end
end
然而,一旦我把抽象类型放入它自己的模块中,它就不再起作用了:
在src/qux.jl
中,我放了:
module qux
abstract type Foo end
howdy(x::Foo)::Union{String, Nothing} = nothing
export Foo, howdy
end # module
然后在reproduce.jl
中我添加了:
using qux
struct Bar <: Foo end
function howdy(x::Bar)::Union{String, Nothing}
"I'm a Bar!"
end
struct Baz <: Foo end
if abspath(PROGRAM_FILE) == @__FILE__
bar = Bar()
s = howdy(bar)
if isa(s, String)
println(s)
end
baz = Baz()
t = howdy(baz)
if isa(t, String)
println(t)
end
end
然后我得到:
julia --project=. reproduce.jl
I'm a Bar!
ERROR: LoadError: MethodError: no method matching howdy(::Baz)
Closest candidates are:
howdy(::Bar) at ~/qux/reproduce.jl:5
Stacktrace:
[1] top-level scope
@ ~/qux/reproduce.jl:18
in expression starting at ~/qux/reproduce.jl:11
发布于 2021-10-30 12:52:16
你的问题在Julia手册中有here解释。
问题是在您的代码中,正如您在这里看到的:
julia> module qux
abstract type Foo end
howdy(x::Foo)::Union{String, Nothing} = nothing
export Foo, howdy
end # module
Main.qux
julia> using .qux
julia> struct Bar <: Foo end
julia> function howdy(x::Bar)::Union{String, Nothing}
"I'm a Bar!"
end
howdy (generic function with 1 method)
julia> methods(howdy)
# 1 method for generic function "howdy":
[1] howdy(x::Bar) in Main at REPL[4]:1
julia> methods(qux.howdy)
# 1 method for generic function "howdy":
[1] howdy(x::Foo) in Main.qux at REPL[1]:5
您有两个不同的howdy
函数,每个函数都有一个方法。一个在qux
模块中定义,另一个在Main
模块中定义。
您要做的是向qux
模块中定义的howdy
函数添加一个方法。我通常会通过使用模块名称限定导出的函数名来完成此操作,因为这是一种明确的方式来表明您想要做什么:
julia> module qux
abstract type Foo end
howdy(x::Foo)::Union{String, Nothing} = nothing
export Foo, howdy
end # module
Main.qux
julia> using .qux
julia> struct Bar <: Foo end
julia> function qux.howdy(x::Bar)::Union{String, Nothing}
"I'm a Bar!"
end
julia> methods(qux)
# 0 methods:
julia> methods(howdy)
# 2 methods for generic function "howdy":
[1] howdy(x::Bar) in Main at REPL[4]:1
[2] howdy(x::Foo) in Main.qux at REPL[1]:5
正如您现在看到的,您有一个具有两个方法的单个howdy
函数,所有方法都将按您所希望的那样工作。
https://stackoverflow.com/questions/69781770
复制相似问题