我想写这个函数:
\nis_almost_zero(x::T)::Bool where {T<:Real} = x \xe2\x89\x88 zero(T)\nRun Code Online (Sandbox Code Playgroud)\n但是,此代码会导致错误:
\njulia> is_almost_zero(x::T)::Bool where {T<:Real} = x \xe2\x89\x88 zero(T)\nERROR: UndefVarError: T not defined\nStacktrace:\n [1] top-level scope\n @ REPL[7]:1\nRun Code Online (Sandbox Code Playgroud)\n使用“完整”语法进行函数定义效果很好:
\njulia> function is_almost_zero(x::T)::Bool where {T<:Real}\n x \xe2\x89\x88 zero(T)\n end\nis_almost_zero (generic function with 1 method)\nRun Code Online (Sandbox Code Playgroud)\n省略返回类型也可以:
\njulia> is_almost_zero(x::T) where {T<:Real} = x \xe2\x89\x88 zero(T)\nis_almost_zero (generic function with 1 method)\nRun Code Online (Sandbox Code Playgroud)\n关于参数方法的文档中给出了类似的工作示例:mytypeof(x::T) where {T} = T。
但是,我想指定返回类型,但显然我不能。错误消息没有告诉我表达式的哪一部分导致了错误,但错误本身看起来与我没有指定的情况类似where部分的情况类似:
julia> is_almost_zero(x::T)::Bool …Run Code Online (Sandbox Code Playgroud)