Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `where` syntax in Julia sensitive to new-line?

Tags:

julia

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)

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 {"

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?

like image 237
Dan Getz Avatar asked May 15 '17 15:05

Dan Getz


1 Answers

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

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.

like image 186
mbauman Avatar answered Nov 01 '22 20:11

mbauman