为什么Julia中的where语法对换行符敏感? [英] Why is `where` syntax in Julia sensitive to new-line?

查看:172
本文介绍了为什么Julia中的where语法对换行符敏感?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在另一个有关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 \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

请注意,这意味着您仍然可以将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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆