我正在 Julia 中编写我的第一个模块。我有一个函数f
将使用向量或范围进行某些计算。我想创建一个此函数的方法,该方法将range
在继续计算之前使用该函数创建一个范围,以便为用户提供一些灵活性。
我写了以下内容:
# 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
。除非双方达成一致,否则不能两者兼得。这导致我想要定义另一个g
将在f
. g
会调用range
并有方法来解释三种可能的情况。
- 用户
length
在调用时指定f
。 - 用户
step
在调用时指定f
。 - 用户在调用时既不指定
length
也不指定,因此使用默认值。step
f
step
我宁愿不创建更多的方法f
来避免#do more stuff with x and r
过度复制。我还想if
尽可能避免声明以利用多次调度并提高效率。虽然,到目前为止,我还没有提出任何解决方案。
我不能g
用关键字参数定义多个方法,因为关键字参数是可选的。
# 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
我也无法将关键字参数转换为常规参数,因为我不知道要传递哪个参数。
# 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