Multi-line expressions

I remember being able to extend expressions over multiple lines without a problem in earlier versions of julia.

How do I wrap an expression over multiple lines now when it gets too long?

Particularly, I want to break at the equals sign below

for j in 2:Nz    #copying the first layer into the entire cube
    X[(Ncell*Ny*Nx*(j-1) .+(1:Ncell*Nx*Ny)),:] =X[1:Ncell*Nx*Ny,:] .+(j-1)*cM;
end

Line breaks after = (or inside a parens, or after an binary operator like .+) are still fine.

3 Likes

ahh, was doing the break before the =
silly mistake

Hi, I realize today, that if you use line breaks after =, the binary operator involved must be on that line. For instance, the following Juia code

N=4;z=zeros(N);
for i in eachindex(z)
    z[i] = i^2-i
end 
z2=similar(z)
for i in eachindex(z2)
    z2[i] = i^2 -
          i   
end 
z3=similar(z)
for i in eachindex(z3)
    z3[i] = i^2
          - i
end 
[z z2 z3]

gives

    4×3 Matrix{Float64}:
    0.0   0.0   1.0
    2.0   2.0   4.0
    6.0   6.0   9.0
   12.0  12.0  16.0

So using - on the following lines after a line breaks does not give the right answer

Yes, in your example, z3[i] = i^2 and -i are parsed and evaluated as separate expressions. (-i is evaluated in the loop but not saved to a variable.) If you want to write expressions this way, parentheses are your friend.

for i in eachindex(z3)
    z3[i] = (i^2
          - i)
end

I’ll amend what @stevengj wrote slightly:

1 Like

Thanks!