繁体   English   中英

如何从另一个 function 中将关键字 arguments 传递到“范围” function 并使用 Z2344521E3186E7C1C425268E 保持用户灵活性?

[英]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将只接受steplength之一。 除非双方达成一致,否则不能两者兼得。 这导致我想要定义另一个 function g ,它将在f内部调用。 g会调用range并有方法来解释三种可能的情况。

  1. 用户在调用f时指定length
  2. 用户在调用f时指定step
  3. 用户在调用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM