简体   繁体   English

在 Julia 的 for 循环中索引函数的名称

[英]Indexing the name of a function in a for loop in Julia

I'm trying to write a for loop to generate multiple functions.我正在尝试编写一个 for 循环来生成多个函数。 I would like to iterate on the name of the functions as well but I can't seem to make it work.我也想迭代函数的名称,但我似乎无法让它工作。 Here's what I want to do:这是我想要做的:

for i = 1:n
    h_[i](x) = i*x
end

I know this doesn't work but I would like something like that.我知道这行不通,但我想要类似的东西。

Thanks!谢谢!

As @laborg mentioned, quite often you don't need/want to use metaprogramming .正如@laborg 提到的, 您通常不需要/不想使用元编程 Since you already try to use array indexing syntax ( h_[i] ) perhaps you should simply create a vector of functions, for example like so:由于您已经尝试使用数组索引语法( h_[i] ),也许您应该简单地创建一个函数向量,例如像这样:

h_ = [x->i*x for i in 1:n]

Here, x->i*x is an anonymous function - a function that we don't care to give a name.这里, x->i*x是一个匿名函数——一个我们不关心命名的函数。 Afterwards you can use actual array indexing to access these different functions and call them.之后,您可以使用实际的数组索引来访问这些不同的函数并调用它们。

Demo:演示:

julia> n = 3;

julia> h_ = [x->i*x for i in 1:n];

julia> h_[1](3)
3

julia> h_[2](3)
6

julia> h_[3](3)
9

No metaprogramming involved.不涉及元编程。

(On a side note, in this particular example a single function h(x;i) = i*x with a keyword argument i would probably the best choice. But I assume this is a simplified example.) (在一个侧面说明,在此特定实例中的单一函数h(x;i) = i*x与关键字参数i 。将可能是最好的选择,但我假定这是一个简化的示例)

You have to evaluate the name of your function:您必须评估函数的名称:

for i = 1:n
    f = Symbol(:h_,i)
    @eval $f(x) = $i*x
end

More on this: https://docs.julialang.org/en/v1/manual/metaprogramming/更多相关信息: https : //docs.julialang.org/en/v1/manual/metaprogramming/

As a general note on meta programming in Julia: It really helps to think twice if meta programming is the best solution, especially as Julia offers a lot of other cool features, eg multiple dispatch .作为 Julia 中元编程的一般说明:如果元编程是最佳解决方案,那么三思而后行真的很有帮助,尤其是因为 Julia 提供了许多其他很酷的功能,例如多分派

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM