类型变量的可访问性

最近读 Hands-on Design Patterns and Best Practices with Julia 这本书的时候,看到 The availability of type variables 这一节的一个例子比较有意思:

mytypes1(a::Array{T,1}, x::S) where {S <: Number, T <: S} = T
mytypes2(a::Array{T,1}, x::S) where {S <: Number, T <: S} = S

看起来没毛病,不过:

julia> mytypes1([1,2,3], 4)
Int64

julia> mytypes2(Signed[1,2,3], 4)
ERROR: UndefVarError: S not defined

对于 mytypes2(Signed[1,2,3], 4)来说,T可以确定是Signed,不过根据where的定义,TS的子类型,这里S可以是Integer, Real, Number或者是Any。由于不能确定其具体类型,所以这里直接报错了。

The moral of the story is don’t assume that a type variable is always defined and accessible from the method, especially for a more complex situation like this.

1赞

京ICP备17009874号-2