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,_) 项的值(类似于在 C++ 中使用 bind) 我不确定是否有本地语法来支持这一点,或者我是否需要研究一些符号表示的东西。任何帮助表示赞赏!

解决方法

您可能正在寻找这个:

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

,

您可能正在寻找函数组合运算符

help?> ∘
"∘" can be typed by \circ<tab>

search: ∘

  f ∘ g

  Compose functions: i.e. (f ∘ g)(args...) means f(g(args...)). The ∘ symbol can be
  entered in the Julia REPL (and most editors,appropriately configured) by typing
  \circ<tab>.

  Function composition also works in prefix form: ∘(f,g) is the same as f ∘ g. The
  prefix form supports composition of multiple functions: ∘(f,g,h) = f ∘ g ∘ h and
  splatting ∘(fs...) for composing an iterable collection of functions.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> map(uppercase∘first,["apple","banana","carrot"])
  3-element Vector{Char}:
   'A': ASCII/Unicode U+0041 (category Lu: Letter,uppercase)
   'B': ASCII/Unicode U+0042 (category Lu: Letter,uppercase)
   'C': ASCII/Unicode U+0043 (category Lu: Letter,uppercase)

  julia> fs = [
             x -> 2x
             x -> x/2
             x -> x-1
             x -> x+1
         ];

  julia> ∘(fs...)(3)
  3.0

所以,例如

julia> g(b) = function(x); x*b; end # modifier function
g (generic function with 1 method)

julia> g(3)(2)
6

julia> f() = 3.14
f (generic function with 1 method)

julia> h = g(2) ∘ f
var"#1#2"{Int64}(2) ∘ f

julia> h()
6.28

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...