2
votes

I'm trying to populate an array of functions in Julia. A minimal example is

function nice()
  i=1
  while true
    f() = i
    produce(f)
    i+=1
  end
end

ye = Task(() -> nice())
funcs = Function[]

for i in [1:2]
  push!(funcs,consume(ye))
  println("Why does this not stay the same???")
  println(funcs[1]())
end 

The problem is that funcs[1] changes from the one that returns 1 to the one that returns 2! Please help me out!

1

1 Answers

2
votes

This solved it. I needed a let command and and f=()->j statement

function nice()
  i=1
  while true
    let j=i
      f=()->j
      produce(f)
    end
    i+=1
  end
end
ye = Task(() -> nice())
funcs = Function[]
for k in [1:2]
  push!(funcs,consume(ye))
end
println(funcs[1]())
println(funcs[2]())