I am not sure if I understood the question, but if the purpose is to
store the function you created before accumulating it in a list, you
could use

function give_funs()
  funs = []
  for i in 1:5
    newfun = () -> i
    funs = [funs, newfun]
  end
  funs
end

Also, accumulating the vector by concatenation may not be idiomatic in
this case. A more compact way would be

function give_funs()
  map((i) -> (() -> i), 1:5)
end

Best,

Tamas

On Thu, Oct 16 2014, Evan Pu <[email protected]> wrote:

> Consider this code:
>
> function give_funs()
>   funs = []
>   for i in 1:5
>     function newfun()
>       i
>     end
>     funs = [funs, newfun]
>   end
>   funs
> end
>
> The intention is to create 5 functions and store them in a list called 
> "funs".
> All the functions take no argument, and when the ith function is called, it 
> returns i.
>
> However, when run...
> funs1 = give_funs()
> funs1[1]() # this should give 1, but instead it gives 5
> funs1[2]() # this should give 2, but instead it gives 5 as well
>
> This is problem goes away if I stop naming the function as "newfun" but 
> instead use ananymous functions like so:
> funs = [funs, () -> i]
> however in real code I would like to give it a name so to be more clear 
> what the function is suppose to compute
>
> It seems that these functions are bound by their function names, and since 
> they're all named "newfun", the compiler over-write the old ones defined 
> earlier.
>
> How should this be resolved?

Reply via email to