Julia and nested functions

A while back I discussed nested functions as they relate to Pascal. Well C never really took to having nested functions… but Julia does. Why are they important? If I want to modularize code while at the same time hiding its implementation. Most people don’t know much about nested functions because they really disappeared with C, and have only made a reappearance with Julia.

There are two main reasons for nesting functions. Firstly they allow for functional decomposition, without over-polluting namespaces. A single outwardly visible function can be defined that implements some algorithm, but relies on internally defined functions to decompose the algorithm into smaller parts. Secondly it simplifies parameter passing. A nested function has access to all the parameters and all of the variables in the scope of the wrapper function, so the calling function does not have to explicitly pass a heap of local state into the nested function. Makes sense right?

And it’s easy to do in Julia. Consider a set of two functions factorial() and fact()fact() is nested within factorial() (this is the same structure that I discussed previously using Pascal).

function factorial(x)

    function fact()
        if (n == 0)
            return 1
        else
            n = n - 1
            return (n+1) * fact()
        end
    end

    n = x
    return fact()
end

f = factorial(5)
println("factorial = ", f)

 

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