Closures/Value capture: Difference between revisions

Content added Content deleted
(Added Racket)
Line 810: Line 810:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>irb(main):001:0> list = {}; (1..10).each {|i| list[i] = proc {i * i}}
<lang ruby>list = {}
(1..10).each {|i| list[i] = proc {i * i}}
=> 1..10
irb(main):002:0> list[3].call
p list[3].call #=> 9
p list[7][] #=> 49
=> 9
i = 5
irb(main):003:0> list[7][]
=> 49</lang>
p list[3].call #=> 9</lang>


This works because ''i'' in <code>(1..10).each {|i| ...}</code> is local to its block. The loop calls the block 10 times, so there are 10 different variables to capture.
This works because ''i'' in <code>(1..10).each {|i| ...}</code> is local to its block. The loop calls the block 10 times, so there are 10 different variables to capture.
Line 822: Line 822:


However, (on both Ruby 1.8 and 1.9) when using a for loop, the loop variable is shared and not local to each iteration:
However, (on both Ruby 1.8 and 1.9) when using a for loop, the loop variable is shared and not local to each iteration:
<lang ruby>irb(main):001:0> list = {}; for i in 1..10; list[i] = proc {i * i}; end
<lang ruby>list = {}
for i in 1..10 do list[i] = proc {i * i} end
=> 1..10
irb(main):002:0> list[3][]
p list[3][] #=> 100
i = 5
=> 100</lang>
p list[3][] #=> 25</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==