The location of Julia functions

I have dozens of helper functions in my program.

First of all, why do I have to put them at the beginning of the program?

Is there a way I can put them in a separate jl file for all these functions?

Thanks.

You don’t have to put them at the beginning. The function definition just needs to be executed to define the function before you call it. Segregate your code into as many .jl files as seems fit and include them Essentials · The Julia Language

1 Like

Or, even better, create a package to contain them!

1 Like

Many thanks. I’m able to use a line of include to put all my functions in a separate file. This is so much cleaner.

Quick addition about a different, but slightly related point: the order of definitions does matter for structs/types. You cannot define a type after it is “mentioned” for the first time (at least for dispatch or as field for other structs, which are very common scenarios).

e.g. this will work (as long as you don’t call foo before defining bar):

foo(x) = bar(x)
bar(x) = 2x

but this will error

foo(x::MyType) = 2 * x.value

struct MyType
    value::Int
end

Of course you can still put earlier definitions into other files though.