指定单行参数函数的 return 类型

Specifying the return type of a one-line parametric function

我想写这个函数:

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)

省略 return 类型也有效:

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

但是,我想指定 return 类型,但显然我不能。错误消息没有告诉我 表达式的哪一部分 导致了错误,但错误本身看起来类似于我没有指定 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,完整语法和“作业形式”应该是相同的:

The traditional function declaration syntax demonstrated above is equivalent to the following compact "assignment form"

的回答说这两种定义函数的方式是“功能相同”和“等价”的。

问题

如何指定像这样的单线参数函数的 return 类型?

is_almost_zero(x::T)::Bool where {T<:Real} = x ≈ zero(T)

当有 return 类型注释时,解析单行代码会出现问题,您可以使用括号来帮助解析器解决问题:

(is_almost_zero(x::T)::Bool) where {T<:Real} = x ≈ zero(T)

在这种特殊情况下,我会推荐

is_almost_zero(x::Real)::Bool = (x ≈ zero(x))

这里不用where