可选参数的 Julia 约定 [英] Julia convention for optional arguments
问题描述
假设我有一个函数,例如 f(x,y)
但 y
参数是可选的.将 y
设置为可选参数的首选方法是什么?一种适合我的选择:
Say I have a function such as f(x,y)
but the y
parameter is optional. What is the preferred way to set y
as an optional argument? One option that works for me:
function f(x, y=nothing)
# do stuff
if y == nothing
# do stuff
else
# do stuff
end
# do stuff
end
但这是首选方式吗?我无法将 y
设置为单个默认值以用于计算,因为当 y
什么都不是时,有许多计算方式不同.我也可以只使用单独的函数 f(x)
和 f(x,y)
但这似乎代码重复太多了.
But is this the preferred way? I can't set y
to a single default value to use in calculation, as there are a number of calculations that are done differently when y
is nothing. I could also just have separate functions f(x)
and f(x,y)
but that seems like too much code duplication.
推荐答案
这很好.请注意,可选参数会导致调度.这意味着 if y == nothing
(或等效地,if typeof(y) <: Void
)实际上会被编译掉.您将获得两个不同的功能,这取决于用户是否给出值.所以最后,if
语句被编译掉了,这样做非常有效.
This is fine. Note that optional arguments cause dispatch. This means that the if y == nothing
(or equivalently, if typeof(y) <: Void
), will actually compile away. You'll get two different functions which depend on whether the user gives a value or not. So in the end, the if
statement compiles away and it's perfectly efficient to do this.
我会注意到,目前关键字参数并非如此.
I will note that the same is not currently true for keyword arguments.
另一种方法是使用两种方法:
Another way to do this is to have two methods:
f(x)
和
f(x,y)
两种方法是否比带有 if
的一种方法更好取决于问题.由于 if
将使用类型信息进行编译,因此除了代码组织之外,这两种方法之间没有区别.
Whether two methods is nicer than 1 method with an if
depends on the problem. Since the if
will compile away using type information, there's no difference between these two approaches other than code organization.
这篇关于可选参数的 Julia 约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!