在朱莉娅中输入参数和内部构造函数0.6

Mic*_*ard 7 julia

我对使用where语法如何使用julia 0.6中的抽象类型限制参数类型的类型参数表示怀疑.

考虑一个示例,我想创建一个采用整数的参数化抽象类型,并定义从中继承的结构.如果我尝试:

abstract type AbstractFoo{T} where T<: Integer end
Run Code Online (Sandbox Code Playgroud)

它失败了,但我可以使用非where语法

abstract type AbstractFoo{T<:Integer} end
Run Code Online (Sandbox Code Playgroud)
  1. 这是推荐的格式吗?

鉴于此,我如何实现我的子类型

mutable struct Foo{T} <: AbstractFoo{T} where T <: Integer
   bar::T
end
Run Code Online (Sandbox Code Playgroud)

也失败了(Invalid subtyping).我可以where再次绕过语法

mutable struct Foo{T<:Integer} <: AbstractFoo{T}
   bar::T
end
Run Code Online (Sandbox Code Playgroud)

但这似乎是多余的(因为T已经被限制为整数).我可以把它留下来吗?:

mutable struct Foo{T} <: AbstractFoo{T}
    bar::T
end
Run Code Online (Sandbox Code Playgroud)

最后,随着内部构造函数语法的弃用,有没有办法将内部构造函数定义为:

mutable struct Foo{T} <: AbstractFoo{T}
    bar::T
    Foo{T}(x::T) where T = new(x)
end
Run Code Online (Sandbox Code Playgroud)

这使得Foo(3)不可能 - 要求我使用Foo{Int}(3).这是故意还是有更好的解决方法?编辑:我想对于内部构造函数问题,我总是可以定义一个外部构造函数Foo(x::T) where {T} = Foo{T}(x).

张实唯*_*张实唯 5

我会写:

abstract type AbstractFoo{T<:Integer} end

mutable struct Foo{T} <: AbstractFoo{T}
    bar::T
    Foo(x::T) where T = new{T}(x)
end
Run Code Online (Sandbox Code Playgroud)

这1)限制x到Integer2)允许写入Foo(2)

关于问题:

  1. 是的,这是正确和唯一正确的格式
  2. 这是有效的,T将被限制Integer,但你可能会得到一个更糟糕的错误信息,因为它来自AbstractFoo,而不是Foo.您的用户可能不会注意到这Foo是一个子类型AbstractFoo并且感到困惑.
  3. 这是有意的,也是引入where语法的主要目的之一.在新语法中,T{S}始终指定类型参数,Twhere S引入函数的类型参数.因此,Foo{T}(x) where T =定义Foo{Int}(2)应该做什么,并Foo(x::T) where T =定义Foo(2)应该做什么.后where经人介绍,不存在"内部构造"了.您可以在任何结构中定义任何函数(不一定是该类型的构造函数),并定义类型定义之外的任何构造函数 - 唯一的区别是内部类型定义,您可以访问new.