Nested functions and scope in Julia

If you have never dealt with nested functions, you haven’t seen what their scope can do. Here’s a piece of code with one function main(). that contains two nested functions at the same level: nested1() and nested2(). Both these nested functions have access to both the parameter i, and the variable k. However, as they sit at the same level, they cannot access each others parameters.

function main(i)

    function nested1(j)
        nested2(8)
    end

    function nested2(j)
        println(i)
        println(j)
        println(k)
    end

    k = 7
    nested1(i)
end

main(5)

Now, if there is a name conflict, i.e. two variables having the same name in different scopes, the variable being used has local scope. For example if nested2() were replaced with the code below,  printing k would print the value 12, as opposed to 7 in the code above.

function nested2(j)
    k = 12
    println(j)
    println(k)
end

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s