Danellb
Danellb

Reputation: 55

Indexing the name of a function in a for loop in Julia

I'm trying to write a for loop to generate multiple functions. 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!

Upvotes: 3

Views: 852

Answers (2)

carstenbauer
carstenbauer

Reputation: 10127

As @laborg mentioned, quite often you don't need/want to use metaprogramming. 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_ = [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. 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.)

Upvotes: 3

laborg
laborg

Reputation: 871

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/

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, e.g. multiple dispatch.

Upvotes: 2

Related Questions