Mutating function in Julia (function that modifies its arguments)

后端 未结 3 1505
孤城傲影
孤城傲影 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:34

    It is possible to assign new values to a constant within a function if you're willing to feed that function a symbol corresponding to the constant as an argument, although I think that some might argue that this doesn't satisfy Julia programming best practices:

    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
    

    Or, if one wanted, a bit more concisely:

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

    For more discussion of a related issue, see this Github discussion

提交回复
热议问题