【问题标题】:Declaring the name of argument when invoking a function调用函数时声明参数的名称
【发布时间】:2020-04-07 19:50:52
【问题描述】:

Julia 1.4.0我有如下功能:

function output(W::Int64,F::Int64,P::Int64,S::Int64)
       return ((W-F+2*P)/S +1)
       end

当我输入以下命令时,输出如预期的那样

julia> output(28,5,0,1)
24.0

现在,为了确定哪个参数是什么,我在调用函数时明确命名它们(如果可能的话,如果可以以不同的顺序编写参数,这将很有帮助)

julia> output(W=28,F=5,P=0,S=1)
ERROR: MethodError: no method matching output(; W=28, F=5, P=0, S=1)
Closest candidates are:
  output(::Int64, ::Int64, ::Int64, ::Int64) at REPL[23]:2 got unsupported keyword arguments "W", "F", "P", "S"
  output(::Any, ::Any, ::Any, ::Any) at REPL[2]:2 got unsupported keyword arguments "W", "F", "P", "S"
Stacktrace:
 [1] top-level scope at REPL[25]:1

还有其他类似的方法吗?

【问题讨论】:

    标签: function arguments julia keyword-argument


    【解决方案1】:

    你想为你的函数使用关键字参数(你可以阅读更多关于关键字参数in the Julia docs

    要使用关键字参数声明您的函数,您应该这样做(注意参数前的分号):

    function output(;W::Int64,F::Int64,P::Int64,S::Int64)
           return ((W-F+2*P)/S +1)
    end
    

    然后,您可以根据需要运行您的函数:

    julia> output(W=28,F=5,P=0,S=1)
    24.0
    

    【讨论】:

    • 非常感谢@ARamirez。确实有效。你知道用分号声明函数有什么好处吗?为什么没有一种声明函数的方式(没有那个分号)?
    • 这是一个很好的问题 - ; 的问题在于它将位置参数与关键字参数分开,并且只有位置参数参与方法分派(参见例如这里的讨论:discourse.julialang.org/t/…)。为了说明,考虑f(x::Number) = "a number!"; f(x::Int) = "an integer!"g(;x::Number) = "a number"; g(;x::Int) = "an integer" 之间的区别。您会发现对于g,只有一种方法存在,因为第二种方法覆盖了第一种方法,而对于f,有一种方法适用于Int,一种方法适用于Float
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多