Julia的方法

Broadcasting, methods and multiple-dispatch

广播,方法和多派遣

This is part 9 of the Julia Tutorials (a series of tutorials on Julia). If you are not familiar with Julia functions, please go through part 8 for better understanding.

这是Julia教程(关于Julia的一系列教程)的第9部分。 如果您不熟悉Julia函数 ,请阅读第8部分,以更好地理解。

If you are not familiar with Julia and want to get started with it, feel free to check out the complete series @ —

如果您不熟悉Julia,并想开始使用它,请随时查看完整的系列@-

Note: Use Julia’s REPL to quickly follow along with the codes in this tutorial

注意:使用Julia的REPL可以快速遵循本教程中的代码

广播 (Broadcasting)

Broadcasting in Julia helps to write performant code. Think of an application where you want to update an iterable such as an array element-wise, the most straight forward approach is iterating through each entry of the array using a for loop and updating them. But, this can be made more efficient by using Julia’s built-in broadcasting operators. We can apply broadcasting on both Julia’s built-in and user defined functions. Broadcasting can be done in 2 ways:

使用Julia进行广播有助于编写性能良好的代码。 考虑一个应用程序,您想在其中更新可迭代对象,例如在数组元素方面,最直接的方法是使用for循环遍历数组的每个条目并更新它们。 但是,可以通过使用Julia的内置广播运营商来提高效率。 我们可以将广播应用到Julia的内置功能和用户定义的功能上。 广播可以通过两种方式进行:

Using broadcast keyword

使用 broadcast 关键字

function increment(a, factor=1)
a += factor
endarr = [1, 2, 3, 4, 5, 6, 7]# Broadcast the increment function over the array
arr = broadcast(increment, arr)

In the above example, the increment function updates the value of the argument a by factor . So when increment is broadcasted over the array arr , each element of arr gets incremented by factor .

在上面的示例中, increment函数通过factor更新参数afactor 。 因此,当increment被广播在阵列arr ,的每个元素arr得到由递增factor

If you want to broadcast over only a certain arguments, it can be done like this:

如果只想广播某些参数,可以这样进行:

arr = broadcast(i -> increment(i, 2), arr)

Using . (vectorized dot) operatorIf you have gone through part 6 of this tutorial series (Operators in Julia), you would probably remember about the vectorized dot operator. Let’s see how we can broadcast our increment function over arr using . operator.

使用 . (矢量化的点)运算符如果您已经学习了本教程系列的第6部分(Julia中的运算符),您可能会记得矢量化的点运算符。 让我们看看如何使用来在arr广播increment函数. 操作员。

arr = increment.(arr)

For broadcasting over only certain arguments, wrap the arguments that shouldn’t be broadcasted inside Ref

为了仅广播某些参数,请包装不应在Ref广播的参数

arr = increment.(Ref(2), arr)

方法和多派遣 (Methods and Multiple-Dispatch)

When same kind of operation needs to be done for different argument types, we can define the same function with different number and types of arguments. i.e, in the case of adding 2 numbers, we can implement the same addition logic in 2 different functions (with same name and different argument types), one for floating point addition and another for integer addition.

当需要对不同的参数类型执行相同类型的操作时,我们可以定义具有不同数量和参数类型的相同函数。 即,在将两个数字相加的情况下,我们可以在两个不同的函数(具有相同的名称和不同的参数类型)中实现相同的加法逻辑,一个用于浮点加法,另一个用于整数加法。

Julia provides such a functionality by which different implementations of the same concept can be implemented easily. Each of these implementations can have different argument type combinations and different behaviors associated with them. The definition of one of these behaviors is termed as a method.

Julia提供了这样的功能,通过它可以轻松实现同一概念的不同实现。 这些实现中的每一个都可以具有不同的参数类型组合以及与之关联的不同行为。 这些行为之一的定义称为方法

In Julia, each time a function is called, the most appropriate method is applied based on it’s arguments. Applying a method when calling a function is known as dispatch. Object-oriented languages ​​traditionally only consider the first argument in dispatch. Julia is different in that it takes all the arguments of the function into account (not just the first) and then chooses which method to call. This is known as multiple dispatch.

在Julia中,每次调用函数时,都会根据其参数应用最合适的方法。 调用函数时应用方法称为dispatch 。 面向对象语言传统上只考虑调度中的第一个参数。 Julia的不同之处在于,它考虑了函数的所有参数(而不仅仅是第一个),然后选择要调用的方法。 这称为多重调度

Multiple dispatch is used by almost all built-in functions and operators in Julia. For example, Julia’s * perform different operations for different types, for numeric types, it involves multiplication, while for strings, it means string concatenation.

Julia中几乎所有内置函数和运算符都使用多重调度。 例如,Julia*对不同类型执行不同的操作,对于数字类型,它涉及乘法,而对于字符串,则意味着字符串串联。

# with numeric types
3 * 2 # Yields 6
3.5 * 2 # Yields 7# with string types
"Good" * " morning" # Yields "Good morning"

To make use of multiple dispatch in our program, we can construct our own methods for a function. Creating a method is pretty much similar to creating a function.

为了在程序中使用多个调度,我们可以为函数构造自己的方法。 创建方法与创建函数非常相似。

Let’s implement different methods for a function to add it’s arguments.

让我们为函数实现不同的方法以添加其参数。

# Method 1
add(x::Number, y::Number) = x + y# Method 2
function add(x::String, y::String)
println("Method 2 invoked")
return "$x $y"
end# Method 3
function add(x, y::String)
return "$x$y"
end# Method 4
function add(x::String, y)
return "$x-$y"
end

In the above example, we have declared 4 methods where:

在上面的示例中,我们声明了4个方法,其中:

  • Method 1: Adds arguments x and y if they are of type Number

    方法1:如果参数xyNumber类型,则将其添加

  • Method 2: Merge arguments separated by a white space if they are of type String

    方法2:合并参数,如果参数的类型为String则用空格隔开

  • Method 3: Merge arguments if the 1st argument is of type Any and the 2nd one a String

    方法3:如果第一个参数的类型为Any ,第二个参数为String则合并参数

  • Method 4: Merge arguments separated by a - if the 1st argument is of type String and the 2nd one is Any

    方法4:合并用-分隔的参数-如果第一个参数的类型为String ,第二个参数为Any

Julia provides methods keyword which returns all the methods constructed for a function. In our example, if we call methods on add , we will get the following:

Julia提供的methods关键字将返回为函数构造的所有方法。 在我们的示例中,如果我们在add上调用methods ,我们将获得以下内容:

# 4 methods for generic function "add":
[1] add(x::String, y::String) in Main at REPL[2]:2
[2] add(x::Number, y::Number) in Main at REPL[1]:1
[3] add(x, y::String) in Main at REPL[3]:2
[4] add(x::String, y) in Main at REPL[4]:2

Now, let’s see how Julia uses multiple dispatch to call our method of best fit.

现在,让我们看看Julia如何使用多重调度来调用最合适的方法。

add(1, 2)                        # Invokes Method 1
add("Good", "morning") # Invokes Method 2
add(4, "ever") # Invokes Method 3
add("method", 4) # Invokes Method 4
Image for post

As you can see, When a function is called, Julia finds the best possible method defined for that function based on all the argument types (and not just the first argument) and invokes the most specialized method available.

如您所见,调用函数时,Julia将基于所有参数类型(而不仅仅是第一个参数)找到为该函数定义的最佳方法,并调用可用的最专门的方法。

翻译自: https://medium.com/@adarshms/methods-in-julia-3eaeaaf75bd2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值