Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions inside a function in Julia

Tags:

julia

In Julia, I have a function for a complicated simulation, monte_carlo_sim() that involves many parameters. Inside this function, I need to call many other functions. I could write stand-alone functions outside of monte_carlo_sim(), but then I'd need to pass many parameters-- many of which are constant inside this function-- which would sacrifice elegance and clarity (and perhaps not take advantage of the fact that these are constant variables?). Is there a performance reason to not include functions within functions? As a toy example here, the temperature T is constant, and if I don't want to pass this variable to my function compute_Boltzmann(), I could do the following. Is there anything wrong with this?

function monte_carlo_sim(temp::Float64, N::Int)
    const T = temp

    function compute_Boltzmann(energy::Float64)
         return exp(-energy/T)
    end

    # later call this function many times
    for i = 1:1000
        energy = compute_energy()
        b = compute_Boltzmann(energy)
    end
end

Alternatively, I could define a new const type SimulationParameters and pass this to compute_Boltzmann instead, and writing compute_Boltzmann outside of the monte_carlo_sim function as here? Is this better? I'd be passing more information than I'd need in this case, though.

like image 849
Cokes Avatar asked Mar 22 '16 20:03

Cokes


People also ask

How do functions work in Julia?

A function in Julia is an object that takes a tuple of arguments and maps it to a return value. A function can be pure mathematical or can alter the state of another object in the program.

What is :: In Julia?

A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .

What is a generic function Julia?

Method Tables Every function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table. Method tables (type MethodTable ) are associated with TypeName s.

What is multiple dispatch Julia?

Using all of a function's arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch.


1 Answers

Since google led me here, perhaps I add a comment:

Nested functions used to be slower, see for instance this discussion on github... in 2013. But not any more: running exactly the tests there on v0.6, they are all the same speed now.

This is still true for me if (like the question) the inner function implicitly depends on things defined within the outer function, which would have to be passed explicitly if it were a free-standing function.

like image 80
improbable Avatar answered Sep 20 '22 15:09

improbable