Wouldn’t it make sense to have a deepsimilar function shipped with Julia, in the same way deepcopy is? For example, for nested array-like objects containing numbers, this could be defined as

function deepsimilar(x::AbstractArray)
	y = similar(x)
	for k in eachindex(x)
		y[k] = similar(x[k])
	return y

deepsimilar{T <: Number}(x::AbstractArray{T}) = similar(x)

I guess for generalizing this I should look into how deepcopy is done.

1 Like

What’s it for?

It’s nice for nested arrays. Another related case is recursive copy! operations, again because copy! on Vector{Vector} will copy over the references and not the values.

I have a small library, RecursiveArrayTools.jl, for holding these kinds of routines because I need them quite often for DiffEq stuff.

I think deepsimilar would do well there, but I would like to see a group of tools dedicated to this in Base since I was surprised I couldn’t find a simple way to do this.

Well, I found myself implementing this in order to be able to represent blocks of variables using Array{Array}. I use deepsimilar to instantiate “copies” (i.e. arrays with the same shape, and whose elements have the same shape, and so on) on which to perform operations, without actually copying the data. I guess when you don’t need to replicate data into the new object, similar-ing it is faster than copy-ing it.

It might make sense also for more structured types other than nested arrays.