微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用关键字参数对复合函数进行别名?

如何解决如何使用关键字参数对复合函数进行别名?

我可以为单个函数添加别名,例如:

julia> f(y;x=1) = x * y
f (generic function with 2 methods)
julia> const g = f
f (generic function with 1 method)
julia> g(3,x=2)
6

但是,如果我尝试使用复合函数来执行此操作,则kwarg会引起麻烦:

julia> const gg= sqrt ∘ f
#62 (generic function with 1 method)
julia> gg(3,x=2)
ERROR: MethodError: no method matching (::Base.var"#62#63"{typeof(sqrt),typeof(f)})(::Int64; x=2)
Closest candidates are:
  #62(::Any...) at operators.jl:875 got unsupported keyword argument "x"

解决方案吗?我正在尝试将参数传递给f,然后通过快捷方式(上述MWE中的gg)来转换结果。

解决方法

您具有以下定义:

∘(f,g) = (x...)->f(g(x...))

,如您所见,它不支持关键字参数。也许您可以打开一个问题,讨论允许他们这样做。

现在,您可以像这样定义自己的版本:

julia> ⋄(f,g) = (x...; kw...)->f(g(x...; kw...))
⋄ (generic function with 1 method)

julia> f(y;x=1) = x * y
f (generic function with 1 method)

julia> const gg = sqrt ⋄ f
#1 (generic function with 1 method)

julia> gg(3,x=2)
2.449489742783178

编辑:

我已切换到其他操作系统,并且我发现在这里并不太清晰。我使用了以下符号:

help?> ⋄
"⋄" can be typed by \diamond<tab>

被定义为是中缀运算符,并且相对容易记住,同时又不掩盖

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。