首页 > 解决方案 > Julia 中有没有办法修改函数 f(x) 使其返回 f(x)*g(x)

问题描述

我在一些研究生研究中遇到了 Julia,并且已经用 C++ 完成了一些项目。我正在尝试将我的一些 C++ 工作“翻译”成 Julia,以比较性能等。

基本上我想做的是从 C++ 中实现类似函数库的东西,这样我就可以做类似的事情

g(x, b) = x*b # Modifier function

A = [1,2,...] # Some array of values

f(x) = 1 # Initialize the function

### This is the part that I am seeking
for i = 1:length(A) 
  f(x) = f(x)*g(x, A[i]) # This thing right here
end
###

然后能够调用f(x)并获取g(x, _)包含的所有术语的值(类似于bind在 C++ 中使用)我不确定是否有本地语法来支持这一点,或者我是否需要研究一些符号表示的东西。任何帮助表示赞赏!

标签: functional-programmingjulia

解决方案


您可能正在寻找这个:

julia> g(x, b) = x * b
g (generic function with 1 method)

julia> bind(g, b) = x -> g(x, b) # a general way to bind the second argument in a two argument function
bind (generic function with 1 method)

julia> A = [1, 2, 3]
3-element Vector{Int64}:
 1
 2
 3

julia> const f = bind(g, 10) # bind a second argument of our specific function g to 10; I use use const for performance reasons only
#1 (generic function with 1 method)

julia> f.(A) # broadcasting f, as you want to apply it to a collection of arguments
3-element Vector{Int64}:
 10
 20
 30

julia> f(A) # in this particular case this also works as A*10 is a valid operation, but in general broadcasting would be required
3-element Vector{Int64}:
 10
 20
 30

特别是为了修复双参数函数的第一个和第二个参数,Julia Base 中的标准函数分别被调用Base.Fix1Base.Fix2


推荐阅读