|
|
|
|
|
by parenthephobia
3568 days ago
|
|
In Ruby, you could do: 10.times.map do |i|
-> { puts i }
end.shuffle.each(&:call)
This makes 10 lambdas which print the current value of the loop and then calls them in random order. Each puts sees a different i.I don't think the behaviour in the article is really a problem with loop variables, but with defer. It is odd that defer packages up the function and its arguments when it is defined. Deferring printing i remembers the value of i at that time, whilst deferring printing &i remembers the (unchanging) address of i. OTOH, having defer remember the values makes things like f = open("file1")
defer f.close()
... do stuff ...
f = open("file2")
defer f.close()
close both files, which is probably what the programmer expected. I think that's pretty horrible code, but either way some people are going to find the results surprising.Go's "problem" is that it can't efficiently give i a new address in each iteration: it'd have to put each one in a new memory location. |
|