Mutating function in Julia (a function that modifies its arguments)

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

I know that there are type functions push!(list, a)that mutate their input, but how can I define one of my own using an exclamation point.

+4
source share
2 answers

!- it’s just an agreement; this is not a requirement for mutating functions.

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

, , . String s, Tuples, Int64 s, Float32 .. , immutable.

, , Vectors. , .

, , , 2. (fill!(v,2) - , , , )

, v :

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

, :

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

, :

, v

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

, :

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

, (, Int64 s), - .

, , , , ( ), . pass , . , () Java

+10

, , , , , Julia :

function modify_constant!(constant_symbol::Symbol, other_arg)
    new_val = eval(constant_symbol) + other_arg
    eval(Main, Expr(:(=), constant_symbol, new_val))
end

y = 2
modify_constant!(:y, 3)

julia> y
5

, , :

function modify_constant!(constant_symbol::Symbol, other_arg)
    eval(Expr(:(+=), constant_symbol, new_val))
end

. Github

+2

Source: https://habr.com/ru/post/1653440/


All Articles