reason for scoping design of for loops

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

reason for scoping design of for loops

Tamas Papp
(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