Julia-以编程方式生成函数数组

Julia-以编程方式生成函数数组,julia,Julia,我想以编程方式生成一个函数数组,其中包含一个循环,以便每个后续函数都依赖于前一个循环 例如,在伪代码中: f_array = [f1, f2, f3] with: f1(x) = x f2(x) = 3 * f1(x) f3(x) = 3 * f2(x) so that I could call: f_array[3](x) and get the result of f3(x) 以下是我尝试过的: # create simple function just to initialize

我想以编程方式生成一个函数数组,其中包含一个循环,以便每个后续函数都依赖于前一个循环

例如,在伪代码中:

f_array = [f1, f2, f3]
with:
f1(x) = x
f2(x) = 3 * f1(x)
f3(x) = 3 * f2(x)

so that I could call:
f_array[3](x)
and get the result of f3(x)
以下是我尝试过的:

  # create simple function just to initialize
  f(x)=x
  
  # initialize array of functions
  N = 3
  f_array = fill(f, N)
  
  # now we update each function
  for i in 2:N
    f_array[i] = (f(x)= 3 * f_array[i-1](x))
  end
我得到一个错误:

错误:MethodError:无法转换getfieldMain类型的对象, Symbolf15{Int64}到typeoff类型的对象

我目前找不到解决办法。任何帮助都将不胜感激。

当您使用f填充时,它会将f_数组元素的预期类型设置为f,在下面的代码中,我将切换到抽象类型,以使数组中的任何函数都成为可能

  # create simple function just to initialize
  f(x)=x
  
  # initialize array of functions
  N = 3
  f_array = Array{Function}(undef, N);
  f_array[1] = f;

  # now we update each function
  for i in 2:N
    f_array[i] = x -> 3 * f_array[i-1](x)
  end

  print(f_array[3](2))
当使用fill with f时,它会产生一个18的值,它将f_数组元素的预期类型设置为f,在下面的代码中,我将切换到抽象类型,以使数组中有任何函数成为可能

  # create simple function just to initialize
  f(x)=x
  
  # initialize array of functions
  N = 3
  f_array = Array{Function}(undef, N);
  f_array[1] = f;

  # now we update each function
  for i in 2:N
    f_array[i] = x -> 3 * f_array[i-1](x)
  end

  print(f_array[3](2))

同时,我还发现了一种使用元编程的方法。我将此贴在这里,因为它可能对其他人有用:

f1(x) = x

for i in 2:N
  prog = "f$i(x) = 3 * f$(i-1)(x)"
  exp = Meta.parse(prog)
  eval(exp)
end

f3(2)
# 18

同时,我还发现了一种使用元编程的方法。我将此贴在这里,因为它可能对其他人有用:

f1(x) = x

for i in 2:N
  prog = "f$i(x) = 3 * f$(i-1)(x)"
  exp = Meta.parse(prog)
  eval(exp)
end

f3(2)
# 18

我会把耶戈尔的回答写成

f_array = Function[identity]
for i in 2:3
     push!(f_array, x -> 3f_array[i-1](x))
end
但更重要的是,这是一种众所周知的模式:迭代函数应用程序。它已经实现了,不是在Base中,而是在中,通过它您应该能够编写:

f_array(start, N) = collect(Iterators.take(iterated(x -> 3x, start), N))

不过,我没有对此进行测试。

我会将耶戈尔的答案写成

f_array = Function[identity]
for i in 2:3
     push!(f_array, x -> 3f_array[i-1](x))
end
但更重要的是,这是一种众所周知的模式:迭代函数应用程序。它已经实现了,不是在Base中,而是在中,通过它您应该能够编写:

f_array(start, N) = collect(Iterators.take(iterated(x -> 3x, start), N))

不过,我没有对此进行测试。

不要使用字符串并解析use:f$ix。。。引号。不要使用字符串并解析使用:f$ix。。。引用