Code organisation: Move functions to the end of the code

Hi all,

I wonder if I aim to code based on a single *.jl (without any external modules etc) if I could move the function definitions at the very low end of my script. Coming from Fortan I used to work like that which made my code appear much cleaner. Can I achieve a similiar behavior in Julia ? So that say the compilation order is changed ?

MWE:

# Input
x = 10.0;
y = 20.0;

# Output
zsum = mysum(x,y);
zprod = myprod(x,y);
println("sum:", zsum);
println("prod:", zprod);


#############################
# Collected Functions
function mysum(a,b)
    c = a+b
end 

function myprod(a,b)
    c = a*b
end

Thank you in advance for your support.

I don’t think you can, although Pluto notebooks work that way - they have n execution order of cells which is independent of the display order, and many people use this to do exactly what you describe here.

Code is evaluated sequentially, so functions need to be defined before they are called.

Here are some alternatives:

  1. Place your functions in another file and include that file at the start of your script:

    include("collected_functions.jl")
    
    # Input
    x = 10.0
    y = 20.0
    # ...
    println("prod:", zprod)
    # EOF
    

    This method visually looks just as clean (if not cleaner) in my opinion, though now you have to deal with another file.

  2. Place your script in a function and call the function at the end of the file (or from the REPL after includeing the file):

    function main()
        # Input
        x = 10.0
        y = 20.0
        # ...
        println("prod:", zprod)
    end
    
    #############################
    # Collected Functions
    # ...
    end
    
    main() # or omit this and from the REPL do include("main.jl"); main()
    

    I do this quite a lot when I’m experimenting and just want to deal with one file. This method keeps basically the same structure you are used to and is faster because you are no longer working in the global scope, but you lose the benefit of having intermediate computations automatically stored in a workspace (i.e., you can’t access zprod after running main, though you can of course manually return the variables you care about inspecting if you have the foresight to do so).

11 Likes

@ceysa75 You can use Stevens solution and then try this:

This should make it possible to develop in a script, getting the performance boost of a function and then being able to extract everything from the function easily.

Kind regards