[英]How can I pass keyword arguments to the `range` function from within another function and maintain user flexibility with Julia?
我正在 Julia 中编写我的第一个模块。 我有一个 function f
它将使用向量或范围进行某些计算。 我想创建一个 function 的方法,该方法将在继续计算之前使用range
function 创建一个范围,以便为用户提供一些灵活性。
我写了以下内容:
# Attempt 1
function f(x,start,stop;length=1001,step=0.1)
r=range(start,stop,length=length,step=step)
# do more stuff with x and r
end
# error: length and step don't agree
但是, range
将只接受step
或length
之一。 除非双方达成一致,否则不能两者兼得。 这导致我想要定义另一个 function g
,它将在f
内部调用。 g
会调用range
并有方法来解释三种可能的情况。
f
时指定length
。f
时指定step
。f
时既不指定length
也不指定step
长,因此使用默认step
值。 我宁愿不创建更多的f
方法以避免过度复制#do more stuff with x and r
。 我还想尽可能避免if
语句,以利用多次调度并提高效率。 虽然,到目前为止,我还没有提出任何解决方案。
我不能用关键字 arguments 定义多个g
方法,因为关键字 arguments 是可选的。
# Attempt 2
function g(start,stop;length=1001)
r=range(start,stop,length=length)
end
function g(start,stop;step=0.1)
r=range(start,stop,step=step)
end
# error: the method definitions overlap
我也无法将关键字 arguments 转换为常规 arguments 因为我不知道要传递哪个参数。
# Attempt 3
function g(start,stop,length)
r=range(start,stop,length=length)
end
function g(start,stop,step)
r=range(start,stop,step=step)
end
function f(x,start,stop;length=1001,step=0.1)
r=g(start,stop,y)
end
# error: no way to determine y or to differentiate length from step when passed to g
range
function 在未指定时不使用nothing
step
长/ length
,因此以下内容应该适合您:
function f(start, stop; step=nothing, length=nothing)
if step === length === nothing
step = 0.1 # default step
end
r = range(start, stop; step=step, length=length)
return r
end
例子:
julia> f(1, 2; step=0.2)
1.0:0.2:2.0
julia> f(1, 2; length=3)
1.0:0.5:2.0
julia> f(1, 2) # default step
1.0:0.1:2.0
我宁愿不创建更多的 f 方法以避免过度复制 #do more stuff with x 和 r
一个比较常见的模式是将核心功能移动到另一个 function,比如说_f
,并有多个入口点f
,它为_f
构造正确的 arguments 。 这是一个草图:
function f(x, y)
# construct arguments with x and y
args = ...
return _f(args...)
end
function f(x, y, z)
# construct arguments with x, y and z
args = ...
return _f(args...)
end
function _f(args...)
# core computation
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.