Quantcast

most generic way to request iterable type as input

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

most generic way to request iterable type as input

Kevin Kunzmann
Hi,

say I want to define a custom type with a field that accepts any kind of iterable integer type as valid input (both 1:3 as well as collect(1:3)), how would I do that in the most generic way? I know that I can use

type test{T<:integer}
 a
::Union{Range{T},Vector{T}}
end

But there might be other iterable integer types that I did not think of during implementation - how can I make the code even more generic?

Best,

Kevin 
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: most generic way to request iterable type as input

Mauro
There is no proper way to do this.  But note that your suggestion below
is not any more performant than just not typing the field.  You could
check in the constructor whether the type can be iterated on:

immutable Test{T}
  a::T
  function Test(a)
    @assert eltype(a)<:Integer
    tmp = [aa in a] # better make sure the compiler does not remove this no-op
    new(a)
  end
end


On Tue, 2016-11-08 at 16:49, Kevin Kunzmann <[hidden email]> wrote:

> Hi,
>
> say I want to define a custom type with a field that accepts any kind of
> iterable integer type as valid input (both 1:3 as well as collect(1:3)),
> how would I do that in the most generic way? I know that I can use
>
> type test{T<:integer}
>  a::Union{Range{T},Vector{T}}
> end
>
> But there might be other iterable integer types that I did not think of
> during implementation - how can I make the code even more generic?
>
> Best,
>
> Kevin
Loading...