类型定义:期望的 UnionAll,得到 TypeVar [英] Type definition: expected UnionAll, got TypeVar

查看:17
本文介绍了类型定义:期望的 UnionAll,得到 TypeVar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 v0.6 的 Julia 手册中,我发现以下内容:

In the Julia manual for v0.6 I find the following:

abstract type Pointy{T} end
struct Point{T} <: Pointy{T}
    x::T
    y::T
end

这很好用,我认为以下内容也应该:

This works fine, and I thought the following should as well:

abstract type Foo{V, F} end
struct Bar{V, F} <: Foo{V, F}
    x::V{F}
end

Bar 的定义却给出了以下错误

The definition of Bar gives, however, the following error

ERROR: TypeError: Type{...} expression: expected UnionAll, got TypeVar

出了什么问题,我怎样才能实现我真正想要的,即指定 V<:AbstractVectorF<:AbstractFloat?

What is wrong, and how can I achieve what I really want, namely to specify that V<:AbstractVector and F<:AbstractFloat?

推荐答案

试试这个:

julia> abstract type Foo{T} end

julia> struct Bar{T<:AbstractFloat,V<:AbstractVector{T}} <: Foo{T}
           x::V
       end

julia> Bar{T}(v::AbstractVector{T}) = Bar{T,typeof(v)}(v) # constructor
Bar

julia> Bar(rand(3))
Bar{Float64,Array{Float64,1}}([0.387467, 0.535419, 0.240748])

julia> Bar(rand(Int, 3))
ERROR: TypeError: Bar: in T, expected T<:AbstractFloat, got Type{Int64}
Stacktrace:
 [1] Bar(::Array{Int64,1}) at ./REPL[4]:1

这篇关于类型定义:期望的 UnionAll,得到 TypeVar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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