Julia: what does the “<:” symbol mean?

亡梦爱人 提交于 2020-11-29 05:58:25

问题


What does this mean in function signatures, for example:

convert(::Type{T}, z::Complex) where {T<:Real}


回答1:


Strictly speaking, one should differentiate between the predicate Base.:(<:), as described in @Saqib's answer, and the syntactic usage of <: for describing constraints.

This syntactic usage can occur in type parameter declarations of methods, to constrain a type variable to be a subtype of some other type:

f(x::T) where {T<:Real} = zero(x)

A sort of special case of this is when you constrain the type parameter of a struct (struct Foo{T<:Real} ... end) -- that constrains the methods of the generated constructor, and allows the type constructor to be applied only to the constrained subtypes.

On the other hand, outside of type parameters, <: can be used to declare a new type as a subtype of some other (necessarily abstract) type:

struct Foo <: Real end

Although both cases are in line with the meaning of the subtyping predicate, you can't replace them with other arbitrary expressions (e.g., you can't write ... where {isreal(T)} in f).




回答2:


<:(T1, T2)

Subtype operator: returns true if and only if all values of type T1 are also of type T2.

Examples:

Float64 <: AbstractFloat
=> true

Vector{Int} <: AbstractArray
=> true

Matrix{Float64} <: Matrix{AbstractFloat}
=> false


来源:https://stackoverflow.com/questions/53015450/julia-what-does-the-symbol-mean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!