内部类型定义是保留的

时间:2015-07-07 23:10:48

标签: julia

在0.3中使用的代码:

type foo
    bar::Int = 0
end

迁移到Julia 0.4后会产生错误,如

julia4 test.jl
ERROR: LoadError: syntax: "bar::Int=0" inside type definition is reserved
 in include at ./boot.jl:254
 in include_from_node1 at loading.jl:133
 in process_options at ./client.jl:306
 in _start at ./client.jl:406

错误是什么意思?如何修复0.4 - ?

NB

我知道它是开发版。我也用谷歌搜索并查阅了手册http://julia.readthedocs.org/en/latest/manual/types/

3 个答案:

答案 0 :(得分:4)

好的,我想到的是使用名为new()的构造函数和一个带有默认(类似python / haskell)参数值的函数(在类型中):

type Foo
    bar::Int

    function Foo(bar=0)
        new(bar)
    end
end


x = Foo()

显然,较短的句法版本现在不起作用:

编辑更短的版本也可以正常工作(thnx @ivarne)

type Foo
    bar::Int

    Foo(bar=0) = new(bar)
end

重要解决方案适用于0.3和0.4,因此无需使用if VERSION .. else .. end

Side注意:如果你在foo类型中有多个变量,你可以在最后一行添加逗号来说明其他变量!

答案 1 :(得分:3)

我认为你所谓的“默认字段值”并不像你预期的那样有效,但在未来(0.6 ish)它可能。见https://github.com/JuliaLang/julia/issues/10146

答案 2 :(得分:3)

内部构造函数用于强制执行不变量,在这种情况下,您只需要定义方法Foo(),注意方法Foo(bar=0)只是创建Foo()

julia> type Foo
           bar::Int
       end

julia> methods(Foo)
4-element Array{Any,1}:
 call(::Type{Foo}, bar::Int64) at none:2
 call(::Type{Foo}, bar) at none:2
 call{T}(::Type{T}, arg) at essentials.jl:56
 call{T}(::Type{T}, args...) at essentials.jl:57

julia> Foo() = Foo(0)
Foo

julia> methods(Foo)
5-element Array{Any,1}:
 call(::Type{Foo}, bar::Int64) at none:2
 call(::Type{Foo}, bar) at none:2
 call(::Type{Foo}) at none:1 <================== Default method
 call{T}(::Type{T}, arg) at essentials.jl:56
 call{T}(::Type{T}, args...) at essentials.jl:57

julia> workspace()

julia> type Foo
           bar::Int
       end

julia> Foo(bar=0) = Foo(bar)
Foo

julia> methods(Foo)
5-element Array{Any,1}:
 call(::Type{Foo}, bar::Int64) at none:2
 call(::Type{Foo}, bar) at none:1
 call(::Type{Foo}) at none:1 <================== Default method
 call{T}(::Type{T}, arg) at essentials.jl:56
 call{T}(::Type{T}, args...) at essentials.jl:57