在Julia的方法中传播类型参数 [英] Propagate Type Parameters in Methods for Julia
本文介绍了在Julia的方法中传播类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在使用类型别名时,Julia(v1.0
)不会在方法定义之外传播自由类型参数:
Julia (v1.0
) is not propagating the free type parameters outside a method definition when using a type alias:
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
却没有:
It seems that rt2
keeps track of the <:Real
upper bound, but rt
does not:
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
约束包含在类似类型别名的语句中?
Is there anyway to automatically include the R<:Real
constraint with a type-alias-like statement?
推荐答案
您可以编写(编辑):
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
中的约束.我不确定这是否有意.
and all works as expected. It looks like where
clause in method definition, if present, overwrites the constraint in const
. I am not sure if this is intended.
这篇关于在Julia的方法中传播类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文