2014-03-04 53 views
8

我现在有与阵列的类型属性声明数组属性的大小的类型定义

immutable foo 
    a::Int64 
    b::Int64 
    x::Array{Float64,1} # One dimension array of Float 64, but no length info 
end 

我知道数组将总是包含100个Float64元件。有没有办法在类型注释中传递这些信息?也许类似于可以声明像x = Array(Float64, 100)这样的实例化数组的大小的方式?

+3

固定大小阵列尚未在朱实现,见[此特性请求(https://github.com/JuliaLang/julia/issues/5857 )在GitHub上。我认为建议你为你的目的使用'NTuple {100,Float64}',但它是不可变的类型(例如setindex!方法未定义等)。 – gagolews

+2

请注意,[issue](https://github.com/JuliaLang/julia/issues/5857)包含可用的实现。 – tholy

回答

3

您可以使用内部构造函数强制不变量。

immutable Foo 
    a::Int64 
    b::Int64 
    x::Vector{Float64} # Vector is an alias for one-dimensional array 

    function Foo(a,b,x) 
     size(x,1) != 100 ? 
     error("vector must have exactly 100 values") : 
     new(a,b,x) 
    end 
end 

然后从REPL:

julia> Foo(1,2,float([1:99])) 
ERROR: vector must have exactly 100 values 
in Foo at none:7 

julia> Foo(1,2,float([1:100])) 
Foo(1,2,[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0 … 91.0,92.0,93.0,94.0,95.0,96.0,97.0,98.0,99.0,100.0])