为什么Julia中的`where`语法对新行敏感?

Dan*_*etz 6 julia

在Stack Overflow上的另一个问题中,答案包括以下函数:

julia> function nzcols(b::SubArray{T,2,P,Tuple{UnitRange{Int64},UnitRange{Int64}}}) where {T,P<:SparseMatrixCSC}
           return collect(i+1-start(b.indexes[2]) 
             for i in b.indexes[2]
             if b.parent.colptr[i]<b.parent.colptr[i+1] && 
               inrange(b.parent.rowval[nzrange(b.parent,i)],b.indexes[1]))
       end
nzcols (generic function with 3 methods)
Run Code Online (Sandbox Code Playgroud)

它被解析没有错误.where为了便于阅读,在添加新行前句时,突然出现错误:

julia> function nzcols(b::SubArray{T,2,P,Tuple{UnitRange{Int64},UnitRange{Int64}}})
        where {T,P<:SparseMatrixCSC}
           return collect(i+1-start(b.indexes[2]) 
             for i in b.indexes[2]
             if b.parent.colptr[i]<b.parent.colptr[i+1] && 
               inrange(b.parent.rowval[nzrange(b.parent,i)],b.indexes[1]))
       end
ERROR: syntax: space before "{" not allowed in "where {"
Run Code Online (Sandbox Code Playgroud)

最后,当参数列表括号移动到该where行时,错误再次消失:

julia> function nzcols(b::SubArray{T,2,P,Tuple{UnitRange{Int64},UnitRange{Int64}}}
        ) where {T,P<:SparseMatrixCSC}
           return collect(i+1-start(b.indexes[2]) 
             for i in b.indexes[2]
             if b.parent.colptr[i]<b.parent.colptr[i+1] && 
               inrange(b.parent.rowval[nzrange(b.parent,i)],b.indexes[1]))
       end
nzcols (generic function with 3 methods)
Run Code Online (Sandbox Code Playgroud)

这种语法背后的逻辑是什么,应该修复吗?

Mat*_* B. 8

这类似于该语言中的许多其他语法; 如果解析器在一行的末尾有一个"完整"语法,它将使用它并继续前进.

julia> parse("begin; 1 \n+ 2; end")
quote  # none, line 1:
    1 # none, line 2:
    +2
end

julia> parse("begin; 1 +\n 2; end")
quote  # none, line 1:
    1 + 2
end
Run Code Online (Sandbox Code Playgroud)

请注意,这意味着您仍然可以将where子句分解为单独的行,但是它where本身需要与函数末尾位于同一行.

  • 旧的语法与参数类型混淆:令人惊讶的是,Point {T}(x :: T)`在`Point`上创建了一个函数,而`Point {T}`上的函数所需的ASCII汤是奇怪的: `(::类型{点【T}})横置(:: T)`.新语法清楚地表明:`Point(x :: T)其中T`或`Point {T}(x :: T)其中T`.https://github.com/JuliaLang/julia/pull/20501#discussion_r99934592 (3认同)
  • 在参数列表中的位置意味着不同的东西:它不是创建跨越所有参数的静态类型参数(并且在函数内可访问),而是创建仅适用于该最终参数的本地类型变量. (2认同)