问题在于朱莉娅的“最佳实践”。我读过这和这。我有个功能
function discount_rate(n, fv, pmt, pv; pmt_type = 0)
...
end现在的问题是,我必须像这样调用这个方法
discount_rate( 10, 10, 10, -10 )还不清楚这些争论意味着什么--甚至我都忘了。我最想做的就是写
discount_rate( n = 10, fv = 10, pmt = 10, pv = -10 )这就更清楚了:更容易阅读和理解。但是,我不能通过设置这些参数( keywords参数或optional参数)来定义我的方法,因为它们没有的自然默认值。从设计的角度来看,有没有推荐的方法来解决这个问题?
发布于 2014-10-19 15:58:07
可以做以下工作:
function discount_rate(;n=nothing,fv=nothing,pmt=nothing,pv=nothing,pmt_type=0)
if n == nothing || fv == nothing || pmt == nothing || pv == nothing
error("Must provide all arguments")
end
discount_rate(n,fv,pmt,pv,pmt_type=pmt_type)
end
function discount_rate(n, fv, pmt, pv; pmt_type = 0)
#...
end发布于 2015-03-10 04:31:35
作为后续,它变得有点乏味,必须(重新)写关键字-仅对应于我已经拥有的功能。在伊恩上面的回答的启发下,我写了一个宏,本质上是这样做的.
macro make_kwargs_only( func, args... )
quote
function $( esc( func ) )( ; args... )
func_args = [ arg[2] for arg in args ]
return $( esc( func ) )( func_args... )
end
end
end因此,例如
f( a, b ) = a/b
@show f( 1, 2 )
f(1,2) => 0.5创建它的关键字-仅对应的
@make_kwargs_only f a b
@show f( a = 1, b = 2 )
f(a=1,b=2) => 0.5注意,这不是一般情况。在这里,争论的顺序是至关重要的。理想情况下,我希望宏对f( a = 1, b = 2 )和f( b = 2, a = 1 )都能以同样的方式工作。情况并非如此。
@show f( b = 2, a = 1 )
f(b=2,a=1) => 2.0所以现在,作为一个黑客,如果我不记得参数的顺序,我就使用methods( f )。任何关于如何重写宏以处理这两种情况的建议都是welcome...maybe --一种根据func的函数签名在宏的函数定义中对func排序的方法
发布于 2019-02-11 03:21:35
值得注意的是,朱莉娅在第0.7节中引入了强制关键字参数:
julia> foo(; a) = a
foo (generic function with 1 method)
julia> foo()
ERROR: UndefKeywordError: keyword argument a not assigned
Stacktrace:
[1] foo() at ./REPL[1]:1
[2] top-level scope at none:0https://stackoverflow.com/questions/26447854
复制相似问题