IsIndexed trait

I’m trying to understand is something like a IsIndexed trait exists already, or not.

This trait would be true for all things which:

  • are collections
  • and for each element there is[1] one key which has O(1) access.

The following (and possibly more) stdlib collection interfaces would evaluate to true: Collections and Data Structures · The Julia Language, although my definition doesn’t require firstindex or lastindex.

I think where such a trait would become interesting would be that iterators could use it to decide whether the underlying datastructure supports views: if IsIndexed(T) then the element of the iterator should be a view of T.

It’s possible that the problem of deciding on whether something should be a view or a copy is already solved generally in a different way and I’m not aware.

[1] exactly one key? possible more? I don’t know.

1 Like

+1. I was thinking of something like IsIndexable.

I’m pretty sure that nothing like this exists. For example this excellent blog post or the linked doc would have surely mentioned it. It’s puzzling to me that nothing like this exists.

Something like this would be useful

maybecollect(v) = IsIndexable(v) ? v : collect(v)

The following works somewhat:

struct IndexNotSupported <: IndexStyle
end
Base.IndexStyle(::Type) = IndexNotSupported()
Base.IndexStyle(x) = IndexStyle(typeof(x))

## Tuple is not an AbstractArray, so this is not defined.
## This must break something somewhere.
Base.IndexStyle(::Type{<:Tuple}) = Base.IndexLinear()

maybecollect(v) = IndexStyle(v) === IndexNotSupported() ? collect(v) : v

This would say that a String is not indexable, which is not true. But a String is not efficiently indexable, and collect gives you vector of the characters, so maybe that’s ok. [EDIT: this agrees with your definition above]

But it’s probably better to make a new trait.

Here is a package implements some of these ideas: