【发布时间】:2021-12-26 22:10:19
【问题描述】:
我想写这个函数:
is_almost_zero(x::T)::Bool where {T<:Real} = x ≈ zero(T)
但是,此代码会导致错误:
julia> is_almost_zero(x::T)::Bool where {T<:Real} = x ≈ zero(T)
ERROR: UndefVarError: T not defined
Stacktrace:
[1] top-level scope
@ REPL[7]:1
对函数定义使用“完整”语法可以正常工作:
julia> function is_almost_zero(x::T)::Bool where {T<:Real}
x ≈ zero(T)
end
is_almost_zero (generic function with 1 method)
省略返回类型也可以:
julia> is_almost_zero(x::T) where {T<:Real} = x ≈ zero(T)
is_almost_zero (generic function with 1 method)
the docs about parametric methods:mytypeof(x::T) where {T} = T 中给出了类似的工作示例。
但是,我想指定返回类型,但显然我不能。错误消息没有告诉我表达式的哪个部分导致错误,但错误本身看起来类似于我没有指定where 部分的情况:
julia> is_almost_zero(x::T)::Bool = x ≈ zero(T)
ERROR: UndefVarError: T not defined
Stacktrace:
[1] top-level scope
@ REPL[23]:1
所以看起来 Julia 没有“看到”我原始代码中的 where {T<:Real} 部分?
这些定义函数的方式应该是等价的吧?
根据the documentation,完整的语法和“赋值形式”应该是相同的:
上面演示的传统函数声明语法等价于以下紧凑的“赋值形式”
this question 的回答说这两种定义函数的方式是“功能相同”和“等效”。
问题
如何指定这样的单行参数函数的返回类型?
is_almost_zero(x::T)::Bool where {T<:Real} = x ≈ zero(T)
【问题讨论】: