在Julia的方法中传播类型参数 [英] Propagate Type Parameters in Methods for Julia

查看:96
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆