Julia 中的变异函数(修改其参数的函数) [英] Mutating function in Julia (function that modifies its arguments)

查看:19
本文介绍了Julia 中的变异函数(修改其参数的函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Julia 中定义变异函数,您希望将结果写入其中一个输入.

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

我知道存在像 push!(list, a) 这样的函数,它们会改变它们的输入,但我如何使用感叹号定义我自己的一个.

I know functions exist like push!(list, a), which mutate their inputs but how can I define one of my own using the exclamation mark.

推荐答案

! 只是一个约定;这不是变异函数的要求.

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 !.

不过,要变异的输入必须是可变的.其中不包括 Strings、Tuples、Int64s、Float32s 等.以及不使用 mutable 关键字定义的自定义类型.

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.

比如说,我们想创建一个函数,用数字 2 替换向量的所有元素.(fill!(v,2) 是执行此操作的 Base 方法.但为了举例)

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)

更改 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

不能修改不可变变量(如Int64s)的原因,是因为它们没有要修改的内容——它们是它们自己的内容.

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

您必须更改传递给函数的变量的内容,而不是更改名称绑定的内容(替换对象)这一概念在许多编程语言中是相当标准的事情.它来自按值传递,其中一些值是引用.我听说它在 Java 中称为 Golden Rule (of References)

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

这篇关于Julia 中的变异函数(修改其参数的函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆