为什么 Julia 中的“where"语法对换行敏感? [英] Why is `where` syntax in Julia sensitive to new-line?
问题描述
在 Stack Overflow 上的另一个问题中,答案包括以下函数:
In a different question on Stack Overflow the answer included the following function:
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)
它被解析没有错误.为了便于阅读,在where
子句前添加换行时,突然出现错误:
And it was parsed without error. When adding a new-line before where
clause for readability, an error suddenly appeared:
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 {"
最后,当参数列表括号移到where
行时,错误又消失了:
Finally, when the parameter list parenthesis is moved to the where
line, the error disappears again:
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)
这种语法背后的逻辑是什么?应该修复它吗?
What is the logic behind this syntax and should it be fixed?
推荐答案
这与语言中的许多其他语法类似;如果解析器在一行的末尾有一个完整"的语法,它将使用它并继续前进.
This is similar to many other syntaxes in the language; if the parser has a "complete" syntax at the end of a line, it'll use that and move on.
julia> parse("begin; 1
+ 2; end")
quote # none, line 1:
1 # none, line 2:
+2
end
julia> parse("begin; 1 +
2; end")
quote # none, line 1:
1 + 2
end
请注意,这意味着您仍然可以将 where
子句拆分为单独的行,但 where
本身需要与函数末尾位于同一行.
Note that this means you can still break the where
clause onto a separate line, but the where
itself needs to be on the same line as the end of the function.
这篇关于为什么 Julia 中的“where"语法对换行敏感?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!