How to construct parametric type with SharedArray or Array, depending on args to constructor?

I would like to construct a parametric type with SharedArrays whenever nprocs()>1, and with standard Arrays when not. I’m trying to understand why this doesnt work:

type V{T}
   array :: T
   function V{T}(arr::T)
       this = new()
       if isa(arr,SharedArray)
            this.array = SharedArray(Float64,(2,2),pids=workers())
       else
            this.array = zeros(2,2)
       end
       return this
    end
end
ERROR: MethodError: Cannot `convert` an object of type SharedArray{Float64,0} to an object of type V{T}
This may have arisen from a call to the constructor V{T}(...),
since type constructors fall back to convert methods.
 in V{T}(::SharedArray{Float64,0}) at ./sysimg.jl:53

where my idea was to say

s = zeros(2,2)
if nprocs()>1
    s = SharedArray{Float64}()
end
# construct
V(s)

You could try putting the conditional in an outer constructor:

type MaybeShared{T <: AbstractArray}
    array::T
end

function MaybeShared(T=Float64, dims=(2,2))
    MaybeShared(nprocs() == 1 ?
                Array{T}(dims...) : SharedArray(T,dims,pids=workers()))
end

MaybeShared() # gives you the array

Also, maybe there is some context missing, but I am not sure I understand what you gain by wrapping the array. You could simply have a function that returns the array of the desired type.

1 Like

yes, that works! thanks.
I need those (many) arrays to be members of a parametric type to be able to organize the workflow better. that’s why I don’t just use a function that spits out a bunch of arrays.

Wrapper types should be declared as immutable.

not if I have to set fields of that type later on.

If there are more fields in that type than the one referencing the wrapped array (i.e. more than in the provided code), then it’s not a “wrapped array” for “workflow organization”, but it’s a whole separate type with its own state (the extra fields), which then has to be mutable. I’m stating the distinction not for theoretical purity, but because it may reveal design defects.

“workflow organization” is the case for me here.