【问题标题】:Declare the size of an array attribute in a type definition在类型定义中声明数组属性的大小
【发布时间】:2014-05-06 10:26:02
【问题描述】:

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

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)

【问题讨论】:

  • Julia 中尚未实现固定大小的数组,请参阅 GitHub 上的 this feature request。我想建议您使用 NTuple{100,Float64} 来满足您的目的,但它是不可变类型(例如 setindex! 方法未定义等)。
  • 请注意,issue 包含一个有效的实现。

标签: julia


【解决方案1】:

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

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

【讨论】:

  • 我认为目前只允许表达式作为内部构造函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多