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

查看:167
本文介绍了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.

推荐答案

!只是一个约定;

任何函数都可以改变其输入. 但是,很显然,它是这样做的,我们在其后缀!.

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

但是,要突变的输入必须是可变的. 其中不包括String,元组,Int64 s,Float32等. 以及用immutable关键字定义的自定义类型.

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

大多数类型都是可变的,例如Vector. 但是您确实需要确保更改其内容, 而不是引用.

Most 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)是执行此操作的基本方法.但是,例如,是这样)

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

您不能修改不可变变量(例如Int64 s)的原因, 是因为它们没有要修改的内容-它们是他们自己的内容.

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

在许多编程语言中,必须更改传入函数的变量的内容,而不是更改名称绑定(替换对象)的概念,这是相当标准的事情.它来自按值传递,其中一些值是引用. 我听说过它称为Java中的<黄金>(参考)黄金法则

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天全站免登陆