Julia's assignment behavior differs from Fortran?

They’re the same — they’re both assignment. It’s the y[1] = 1.0 and y[1] = 2.0 bit that’s mutation. Without that, arrays and scalars behave the same. Example:

function example_no_mut_scalar()
    xOld = 1
    xNew = 2
    xOld = xNew
    println("xOld = ",xOld,", xNew = ",xNew)
    return
end

function example_no_mut_array()
    xOld = [1]
    xNew = [2]
    xOld = xNew
    println("xOld = ",xOld,", xNew = ",xNew)
    return
end

They work the same way:

julia> example_no_mut_scalar()
xOld = 2, xNew = 2

julia> example_no_mut_array()
xOld = [2], xNew = [2]

The example you were surprised by involves mutation of an array, which cannot be done in the scalar case because integers are not mutable.

function example_mut_scalar()
    xOld = 1
    xNew = 2
    xOld = xNew
    xNew[1] = 1 # not actually possible
    println("xOld = ",xOld,", xNew = ",xNew)
    return
end

function example_mut_array()
    xOld = [1]
    xNew = [2]
    xOld = xNew
    xNew[1] = 1
    println("xOld = ",xOld,", xNew = ",xNew)
    return
end

These behave differently, but only in that mutating a scalar is an error:

julia> example_mut_scalar()
ERROR: MethodError: no method matching setindex!(::Int64, ::Int64, ::Int64)

julia> example_mut_array()
xOld = [1], xNew = [1]

Bottom line: no matter what kind of object you’re dealing with when you do x = y then x points at the same object as y.

10 Likes