检查类型是否在Julia中实现了接口

检查类型是否在Julia中实现了接口,julia,Julia,如何在Julia中检查类型是否实现了接口 例如,迭代接口由函数start,next,done实现 我需要的是,根据参数类型是否实现给定接口,对函数进行专门化 编辑 下面是我想做的一个例子 考虑以下代码: a = [7,8,9] f = 1.0 s = Set() push!(s,30) push!(s,40) function getsummary(obj) println("Object of type ", typeof(obj)) end function getsumma

如何在Julia中检查类型是否实现了接口

例如,迭代接口由函数
start
next
done
实现

我需要的是,根据参数类型是否实现给定接口,对函数进行专门化

编辑

下面是我想做的一个例子

考虑以下代码:

a = [7,8,9]
f = 1.0    
s = Set()
push!(s,30)
push!(s,40)

function getsummary(obj)
  println("Object of type ", typeof(obj))
end

function getsummary{T<:AbstractArray}(obj::T)
  println("Iterable Object starting with ", next(obj, start(obj))[1])
end

getsummary(a)
getsummary(f)
getsummary(s)
这就是我们所期望的,因为
Set
不是
AbstractArray
。但是很明显,我的第二种方法只需要T类型来实现迭代接口

我的问题不仅与迭代接口有关,还与一组函数定义的所有接口有关

编辑-2

我想我的问题与


因为我们可以想象像
T这样的东西,所以您可以通过
方法检查
类型
是否实现了
接口
,如下所示:

foo(a_type::Type, an_interface::Symbol) = an_interface ∈ [i.name for i in methodswith(a_type, true)]

julia> foo(EachLine, :done)
true
但是我不太理解您在评论中提到的动态分派方法,通用函数是什么样子的?函数的输入和输出是什么?我猜你想要这样的东西


或者使用一些元编程工具在编译时分别生成这些函数?

通常,这是通过traits完成的。见一个实施方案;在
Base
中使用了类似的方法来调度
Base.iteratorsize
Base.linearindexing
等。例如,这就是
Base
如何使用
iteratorsize
特性实现
收集

"""
    collect(element_type, collection)

Return an `Array` with the given element type of all items in a collection or iterable.
The result has the same shape and number of dimensions as `collection`.
"""
collect{T}(::Type{T}, itr) = _collect(T, itr, iteratorsize(itr))

_collect{T}(::Type{T}, itr, isz::HasLength) = copy!(Array{T,1}(Int(length(itr)::Integer)), itr)
_collect{T}(::Type{T}, itr, isz::HasShape)  = copy!(similar(Array{T}, indices(itr)), itr)
function _collect{T}(::Type{T}, itr, isz::SizeUnknown)
    a = Array{T,1}(0)
    for x in itr
        push!(a,x)
    end
    return a
end
另请参见关于特质的内容

我将定义一个
易变性(::T)
特征如下:

immutable Iterable end
immutable NotIterable end
iterability(T) =
    if method_exists(length, (T,)) || !isa(Base.iteratorsize(T), Base.HasLength)
        Iterable()
    else
        NotIterable()
    end
这似乎有效:

julia> iterability(Set)
Iterable()

julia> iterability(Number)
Iterable()

julia> iterability(Symbol)
NotIterable()

如果我理解正确,您正在寻找
methodswith()
?@gnimuk。是的,差不多。但是我看不到一种使用
methodswith()实现动态分派的干净方法
:我想定义两个函数,根据类型是否实现了接口,将使用正确的函数。我理解您的解决方案,但此julia代码比相应的java代码更详细:)julia中是否有更干净的方法来检查它?@IssamT。因此,这个问题可以简化为
仅仅知道一个类型/“类”`T`,如何找到它的“方法”
。由于julia具有多分派功能,类没有自己的方法,因此这个过程比其他oop语言(如python和java)要困难一些。谢谢。这绝对是我想要的。
immutable Iterable end
immutable NotIterable end
iterability(T) =
    if method_exists(length, (T,)) || !isa(Base.iteratorsize(T), Base.HasLength)
        Iterable()
    else
        NotIterable()
    end
julia> iterability(Set)
Iterable()

julia> iterability(Number)
Iterable()

julia> iterability(Symbol)
NotIterable()