2
votes

I'd like to define in Julia a composite type which contains a variable length array of another composite type. It's better explained by an example. Let's say I have the type

type p 
    c::Int
    p() = new(0)
end

which I don't really care about. The problem is when I try to define the type

type pp 
   len::Int
   arr::Array{p}(1, len)
end

Obviously I get an error like "len not defined" and I don't know how to fix it. Moreover, how should I define then the constructor of type pp? I'm new to Julia and I'm not even sure if what I'm asking is actually possible.

1
you can also use FixedSizeArrays.jl to ensure the arr is of length len.Gnimuc

1 Answers

7
votes

The things that go on the right-hand side of the :: need to be types. The expression Array{p}(1, len) isn't a type; it actually creates an array:

julia> len = 3
       Array{p}(1, len)
1×3 Array{p,2}:
 #undef  #undef  #undef

It's uninitialized, but you can see that it's an array itself (and not the type of an array). Its type is simply Array{p,2}. So the minimal fix for your example is simply:

type pp 
   len::Int
   arr::Array{p,2}
end

That's not really what you want, though. You probably just need a vector of p (and not a row matrix, which is what Array{p}(1,len) will create). Also note that Julia's arrays are very full-featured. You don't need to keep track of the length yourself; the arrays do that already.

So I'd probably write a PP type like this:

immutable PP
    arr::Vector{p} # Vector{p} is an alias for Array{p, 1}
end
PP(len::Int) = PP(Vector{p}(len))