Semi-deep copy of array

I have defined a struct MyType and the corresponding method copy(a::MyType).

Now I would like to have a method to copy an Array of MyType, applying this method to each element of the array. What is the proper Julian way of doing it?

RecursiveArrayTools.jl recursivecopy. Add a dispatch for your MyType.

2 Likes

Your code below:

function recursivecopy(a)
  deepcopy(a)
end

recursivecopy(a::Union{SVector,SMatrix,SArray,Number}) = copy(a)

function recursivecopy(a::AbstractArray{T,N}) where {T<:Number,N}
  copy(a)
end

function recursivecopy(a::AbstractArray{T,N}) where {T<:AbstractArray,N}
  map(recursivecopy,a)
end

Here, none of the specific methods appears to be applicable to MyType.

So I would extend it like this:

function recursivecopy(a::AbstractArray{T,N}) where {T::MyType,N}
  map(recursivecopy,a)
end

function recursivecopy(a::MyType)
  myspecialcopy(a)
end

Is that correct?

Meaning if I don’t have nested arrays I don’t actually call any of your code, but your code shows me how to implement the function.

Thank you!

Yup that’s the right way to do it. Or just add a dispatch to copy for you type, and it’ll automatically find it when it recurses.

I wanna add this to Base sometime.

1 Like

That’s actually what I have already done, here I put myspecialcopy(a) just to show that it’s not the standard copy

1 Like

Alternatively, wouldn’t copy.(a) work?

1 Like

Only if you have one level. FWIW, I want recursive broadcasting too.

By the sounds of it OP only has one level

For what I asked – yes, copy.(a) would work. Well, that’s that simple.