Super type for all things iterable?

Is there such a type? Or is there a way that I can check whether something is iterable?

Thanks

No. You could check with hasmethod though. But most of the times it doesn’t matter. The question is: what do you want to do with the things not iterable? If there is no fallback strategy for things that are not iterable in your case, then it is often not harmful to just call iterate and let the function fail naturally with a method error if a non-iterable is passed as argument. This is how it is done in functions such as

mean(MyType())
ERROR: MethodError: no method matching iterate(::MyType)
2 Likes

I want to collect all things iterable and convert them into an array to perform some operations, as for things not iterable, I simply want to ignore them.

Thanks

function f(itr::TypeForThingsIterable)
    arr=collect(itr)
    #perform some operations
end

Maybe:

julia> function f(itr::T) where T
       if hasmethod(iterate, Tuple{T})
         # do something
       else
         # do nothing
       end
       end

hasmethod is not pure, so you get a runtime check of the method table. This probably wants to be a trait instead.

2 Likes

But if you want to make it an automatic trait which does static dispatch, you’d have to use a generated function, which should not use hasmethod (although I’m guilty of doing this myself https://github.com/mauro3/SimpleTraits.jl/blob/916feab13502003d25e9c04e352aaced4d2509cc/src/base-traits.jl#L69).