Set 和 Array 之间是否有 Collection 超类型?如果不是,一个函数如何在集合和数组上都是多态的(用于迭代)?

Amo*_*mon 3 collections julia

Julia 中是否有一种Collection类型,并且SetArray派生自 ?

我有两个:

julia> supertype(Array)
DenseArray{T,N} where N where T

julia> supertype(DenseArray)
AbstractArray{T,N} where N where T

julia> supertype(AbstractArray)
Any
Run Code Online (Sandbox Code Playgroud)

和:

julia> supertype(Set)
AbstractSet{T} where T

julia> supertype(AbstractSet)
Any
Run Code Online (Sandbox Code Playgroud)

我试图实现的是编写可以同时接受ArraySet作为参数的函数,因为只要我可以迭代它,集合的类型就无关紧要。

function(Collection{SomeOtherType} myCollection)
    for elem in myCollection
        doSomeStuff(elem)
    end
end
Run Code Online (Sandbox Code Playgroud)

Jak*_*sen 5

不,没有Collection类型,也没有类型Iterable

从理论上讲,您可以通过特征来完成您的要求,您可以在别处阅读这些特征。但是,我认为,你应该不会在这里使用的特质,而是简单地从你的限制参数传递给函数的类型避免。也就是说,而不是做

foo(x::Container) = bar(x)
Run Code Online (Sandbox Code Playgroud)

, 做

foo(x) = bar(x)
Run Code Online (Sandbox Code Playgroud)

不会有性能差异。

  • 这就是动态语言的诅咒。你只是让它在那里失败。Julia 中的可迭代对象被精确定义为“`Base.iterate` 起作用的东西”。 (3认同)