How can this closure test be written in other languages?

Posted by Jian Lin on Stack Overflow See other posts from Stack Overflow or by Jian Lin
Published on 2010-04-29T05:34:47Z Indexed on 2010/04/29 5:37 UTC
Read the original article Hit count: 267

Filed under:
|
|
|
|

I wonder how the following closure test can be written in other languages, such as C and Java. Can the same result be expected also in Perl, Python, and PHP?

Ideally, we don't need to make a new local variable such as x and assign it the value of i inside the loop, but just so that i has a new copy in the new scope each time. (if possible). (some discussion is in this question.)

The following is in Ruby, the "1.8.6" on the first line of result is the Ruby version which can be ignored.

p RUBY_VERSION

$foo = []

(1..5).each do |i|
  $foo[i] = lambda { p i }
end

(1..5).each do |j|
  $foo[j].call()
end

the print out is:

[MacBook01:~] $ ruby scope.rb
"1.8.6"
1
2
3
4
5
[MacBook01:~] $ 

Contrast that with another test, with i defined outside:

p RUBY_VERSION

$foo = []

i = 0

(1..5).each do |i|
  $foo[i] = lambda { p i }
end

(1..5).each do |j|
  $foo[j].call()
end

the print out:

[MacBook01:~] $ ruby scope2.rb
"1.8.6"
5
5
5
5
5
[MacBook01:~] $ 

© Stack Overflow or respective owner

Related posts about scope

Related posts about closures