gpt4 book ai didi

struct - Julia 结构错误 "no method matching iterate"

转载 作者:行者123 更新时间:2023-12-02 18:20:25 25 4
gpt4 key购买 nike

在尝试理解 Julia 中的参数结构时,我将以下结构定义为 AbstractSet 的子类型

struct MySet{T} <: AbstractSet{T}
st::Vector{T}
MySet(x::Vector{T}) where {T} = new{T}(x)
end

但是,当我尝试创建 MySet 类型的新对象时,出现以下错误

julia> MySet([1,2])

MethodError: no method matching iterate(::MySet{Int64})
Closest candidates are:
iterate(::Union{LinRange, StepRangeLen}) at ~/julia-1.7.1-linux-x86_64/julia-
1.7.1/share/julia/base/range.jl:826
iterate(::Union{LinRange, StepRangeLen}, ::Integer) at ~/julia-1.7.1-linux-
x86_64/julia-1.7.1/share/julia/base/range.jl:826
iterate(::T) where T<:Union{Base.KeySet{<:Any, <:Dict},
Base.ValueIterator{<:Dict}} at ~/julia-1.7.1-linux-x86_64/julia-
1.7.1/share/julia/base/dict.jl:695

有人可以帮助我理解为什么会出现此错误。

最佳答案

MySet 对象被创建,如下所示:

julia> x = MySet([1,2]);

julia> x.st
2-element Vector{Int64}:
1
2

问题是显示不正确。原因是 AbstractSet 有一个自定义的 show 方法,该方法假设您的 AbstractSet 对象是可迭代的。

要了解在 AbstractSet 被记录之前应实现的最小方法集,您可以通过编写以下内容来了解​​:

julia> subtypes(AbstractSet)
5-element Vector{Any}:
Base.IdSet
Base.KeySet
BitSet
Set
Test.GenericSet

julia> using Test

julia> methodswith(GenericSet)
[1] isempty(s::GenericSet) in Test
[2] iterate(s::GenericSet, state...) in Test
[3] length(s::GenericSet) in Test

我选择 GenericSet 的原因是它被记录为:

help?> GenericSet
search: GenericSet GenericString GenericDict GenericOrder GenericArray

The GenericSet can be used to test generic set APIs that program to
the AbstractSet interface, in order to ensure that functions can work
with set types besides the standard Set and BitSet types.

因此,GenericSet 定义的内容应该是 AbstractSet 接口(interface)所需的最小值。

(上面我向您展示了可以用来发现所需内容的完整过程,因为如果没有前面的步骤,猜测应该检查 GenericSet 是不明显的)

关于struct - Julia 结构错误 "no method matching iterate",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70969308/

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