Mutating function in Julia (function that modifies its arguments)

后端 未结 3 1524
孤城傲影
孤城傲影 2021-02-05 13:54

How do you define a mutating function in Julia, where you want the result to be written to one of it\'s inputs.

I know functions exist like push!(list, a),

3条回答
  •  忘掉有多难
    2021-02-05 14:11

    The ! is just a convention; it is not a requirement for mutating functions.

    Any function can mutate its inputs. But so that it is clear that it is doing so, we suffix it with a !.

    The input to be mutated does have to be mutable, though. Which excludes Strings, Tuples, Int64s, Float32s etc. As well as custom types defined without the mutable keyword.

    Many types are mutable, like Vectors. But you do need to be sure to be changing their contents, rather than the references to them.

    Say, for example, we want to make a function that replaces all elements of a vector with the number 2. (fill!(v,2) is the Base method to do this. But for example's sake)

    what will work

    Changing what v contains:

    function right1_fill_with_twos!(v::Vector{Int64})
        v[:]=[2 for ii in 1:length(v)]
    end
    

    Which is the same as:

    function right2_fill_with_twos!(v::Vector{Int64})
        for ii in 1:length(v)
            v[ii]=2
        end
        v 
    end
    

    So what won't work:

    is changing thing what that name v points to

    function wrong1_fill_with_twos!(v::Vector{Int64})
        v=[2 for ii in 1:length(v)]
    end
    

    Which is the same as:

    function wrong2_fill_with_twos!(v::Vector{Int64})
        u = Vector{Int64}(length(v))
        for ii in 1:length(v)
            u[ii]=2
        end
        v = u 
    end
    

    The reason you cannot modify immutable variables (like Int64s), is because they don't have contents to modify -- they are their own contents.

    This notion that you must change the Content of a variable passed in to a function, rather than change what the name is bound to (replacing the object) is a fairly standard thing in many programming languages. It comes from pass by value, where some values are references. I've heard it called the Golden Rule (of References) in Java

提交回复
热议问题