reason for scoping design of for loops

133 views
Skip to first unread message

Tamas Papp

unread,
May 2, 2016, 7:21:21 AM5/2/16
to julia-dev
(I posted this in julia-users and did not get a reply, maybe because it
is a question about a design choice, so I am trying here).

For loops allocate new variables iff it introduces them, eg

function test1()
l = []
for i in 1:2
push!(l, ()->(j=i; i=i+1; j))
end
l
end

function test2()
l = []
i = 9 # note: only different line
for i in 1:2
push!(l, ()->(j=i; i=i+1; j))
end
l
end

function testl(l)
for i in 1:5
l[1]()
end
l[2]()
end

testl(test1()) # 2
testl(test2()) # 7

While I understand the rule and it is in accordance with the
documentation and thus not a bug, I am curious about the reasons behind
this design. At a first glance, it seems it could be a source of subtle
bugs, so there must be some advantages to balance that.

(I have searched the issues but 'for' is so common that I could not
locate anything useful --- sorry if this was discussed before).

Best,

Tamas
Reply all
Reply to author
Forward
0 new messages