julia - 在类型定义中声明数组属性的大小

标签 julia

我目前有一个具有数组属性的类型

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) ?

最佳答案

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

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])

关于julia - 在类型定义中声明数组属性的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22175581/

相关文章:

julia - 为什么我在 Juno 工作区中看不到任何变量?

for-loop - Julia 中的 for 循环 - 遍历整个索引

types - 在闭包中使用多个方法构造函数,以及错误 "syntax: local variable T cannot be used in closure declaration"

arrays - 使用 Julia 的数组参数调用 Fortran 子程序

julia - Julia REPL 中仅允许有限输出的选项是什么?

matrix - 为什么简单的矩阵乘法会在 Julia 中占用如此多的垃圾收集器时间?

multidimensional-array - Julia 跳跃 : define a multidimensional variable when a dimension depends on other dimension

julia - 如何在 Julia 中添加包

arrays - Julia :在二维数组中变换数组的数组

linear-algebra - 就地元素矩阵乘法又名 Schur Product 又名 Hadamard Product?