多重分发是什么,如何在Julia中使用它?

5

我经常听到关于Julia语言允许“多重派发”的说法,但我并不确定这意味着什么或者看起来是什么样子的。请问有人能够提供一个编程示例以及它所实现的功能吗?

1个回答

10
The choice of which method to execute when a function is applied is called dispatch. Julia allows the dispatch process to choose which of a function's methods to call based on the number of arguments given, and on the types of all of the function's arguments. This is different than traditional object-oriented languages, where dispatch occurs based only on the first argument, which often has a special argument syntax, and is sometimes implied rather than explicitly written as an argument. Using all of a function's arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch. Multiple dispatch is particularly useful for mathematical code, where it makes little sense to artificially deem the operations to "belong" to one argument more than any of the others: does the addition operation in x + y belong to x any more than it does to y? The implementation of a mathematical operator generally depends on the types of all of its arguments. Even beyond mathematical operations, however, multiple dispatch ends up being a powerful and convenient paradigm for structuring and organizing programs.
简而言之:其他语言依赖于方法的第一个参数来确定应调用哪个方法,而在Julia中,多个参数都会被考虑在内。这使得可以定义多个类似函数的定义,它们具有相同的初始参数。
Julia中多分派的一个简单示例可以在这里找到。

6
我建议您观看这个视频 https://www.youtube.com/watch?v=kc9HwsxE1OY ,讲话开始于2.25。 - Michael K. Borregaard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接