Stream: helpdesk (published)

Topic: Create a new instance of a type after indexing


view this post on Zulip Alex Knudson (Aug 27 2021 at 23:08):

Let's say that I have a type defined as

struct MyVectorType{T} <: AbstractVector{T}
    x::Vector{T}
end

I would like to be able to define getindex such that when I do

A = MyVectorType([1, 1, 2, 3, 5, 8])
A[3]

I get 2, and if I do

A[[1, 3, 5]]
A[1:3]

I'll get MyVectorType([1,2,5]) and MyVectorType([1,1,2]), i.e. a new instance of MyVectorType.

view this post on Zulip Gunnar Farnebäck (Aug 28 2021 at 20:10):

You mean something like this?

Base.getindex(x::MyVectorType, i::AbstractVector) = MyVectorType(x.x[i])
Base.getindex(x::MyVectorType, i) = x.x[i]

view this post on Zulip Alex Knudson (Aug 31 2021 at 04:29):

Unfortunately I've already tried something similar to this and it doesn't work. I get an error

ERROR: LoadError: MethodError: Cannot `convert` an object of type
  Int64 to an object of type
  MyVectorType

view this post on Zulip Gunnar Farnebäck (Aug 31 2021 at 08:32):

I can't guess what you did to get there. Can you give a complete example that reproduces it?


Last updated: Dec 28 2024 at 04:38 UTC