我想限制函数的参数返回类型(某个函数的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这显然不是我想要的。有办法在朱莉娅身上实现这一点吗?
发布于 2021-10-28 14:52:46
尝试:
function f()::Vector{<:Real}
return [5]
end现在:
julia> f()
1-element Vector{Int64}:
5https://stackoverflow.com/questions/69756313
复制相似问题