在Julia的方法中传播类型参数

时间:2019-02-12 17:46:51

标签: types julia

使用类型别名时,Julia(v1.0)不会在方法定义之外传播自由类型参数:

const RT{R<:Real} = Type{R}

rt(::RT{R}) where R = R
rt2(::Type{R}) where {R<:Real} = R
# there's more logic here for other subtypes 

这对R<:Real很好:

julia> rt(Int), rt2(Int) # works for both
(Int64, Int64)

但是rt()自由接受非<:Real输入

julia> rt(Char)
Char

julia> rt2(Char)    
MethodError: no method matching rt2(::Type{Char})

似乎rt2跟踪着<:Real的上限,但是rt却没有:

julia> methods(rt)
# 1 method for generic function "rt":
[1] rt(::Type{R}) where R in Main at REPL[2]:1

julia> methods(rt2)
# 1 method for generic function "rt2":
[1] rt2(::Type{R}) where R<:Real in Main at REPL[3]:1

总有没有自动将R<:Real约束包含在类似类型别名的语句中?

1 个答案:

答案 0 :(得分:2)

您可以编写(编辑):

rt(r::RT) = r

现在

julia> methods(rt)
# 1 method for generic function "rt":
[1] rt(r::Type{R} where R<:Real) in Main at REPL[16]:1

julia> rt(Int)
Int64

,所有工作均按预期进行。看起来方法定义中的where子句(如果存在)将覆盖const中的约束。我不确定这是否有意。