2

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!

0

1 Answer 1

2

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]())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.