繁体   English   中英

Julia 限制参数返回类型

[英]Julia restrict parametric return type

我想限制函数的参数返回类型(某事物的Vector )。

假设我有一个函数f定义如下:

julia> function f()::Vector{Real}
           return [5]
       end
f (generic function with 1 method)

我使用Vector{Real}是因为我不想过多地限制自己 - 返回值有时可能会更改为[5.0]

问题是,这会导致5强制转换Real - Julia 基本上忘记了特定类型:

julia> f()
1-element Vector{Real}:
 5

julia> typeof(f())
Vector{Real} (alias for Array{Real, 1})

请注意,如果没有参数类型,则情况并非如此:

julia> function g()::Real
           return 5
       end
g (generic function with 1 method)

julia> g()
5

julia> typeof(g())
Int64

我本来希望像下面这样的事情是可能的:

julia> function f()::Vector{T} where T<:Real
           return [5]
       end
f (generic function with 1 method)

julia> f()
ERROR: UndefVarError: T not defined
Stacktrace:
 [1] f()
   @ Main ./REPL[7]:2
 [2] top-level scope
   @ REPL[8]:1

但是,这仅适用于用于参数的参数类型:

julia> function f(t::T)::Vector{T} where T<:Real
           return [5]
       end
f (generic function with 2 methods)

julia> f(5)
1-element Vector{Int64}:
 5

这显然不是我想要的。 有没有办法在 Julia 中实现这一目标?

尝试:

function f()::Vector{<:Real}
    return [5]
end

现在:

julia> f()
1-element Vector{Int64}:
 5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM