如何解决函数签名中的“ UndefVarError:未定义”

时间:2019-10-06 00:00:27

标签: types julia

我正在尝试运行看起来像其他人的代码

function f{T<:Number}(n::Int, alpha::T, beta::T)
    ...
end

“使用”该文件时,我得到

UndefVarError: T not defined
Stacktrace:
 [1] top-level scope at [file location]:[line number of function definition above]

从我在文档(https://docs.julialang.org/en/v1/base/numbers/)中阅读的内容来看,以上语法似乎正确。知道为什么我会收到此错误吗?

1 个答案:

答案 0 :(得分:4)

这是古老的Julia语法。该函数应按以下方式重写,否则您将需要切换到Julia 0.6或之前的版本之一。

function f(n::Int, alpha::T, beta::T) where {T<:Number}
    ...
end

我在Julia 0.7上运行了以下代码,这就是我得到的:

julia> function f{T<:Number}(n::Int, alpha::T, beta::T)
           print("Test")
       end
┌ Warning: Deprecated syntax `parametric method syntax f{T <: Number}(n::Int, alpha::T, beta::T)` around REPL[1]:2.
│ Use `f(n::Int, alpha::T, beta::T) where T <: Number` instead.
└ @ REPL[1]:2
f (generic function with 1 method)

Here is the link to the general syntax for the where keyword.

Here is the link to a similar StackOverflow post explaining what the where keyword does.