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
的1种方法更好?取决于问题.由于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屋!