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.
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
Or, even better, create a package to contain them!
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.
More specifically, argument annotations access the value of the name at definition-time, just as an assignment x = MyType does when executed. The foo(x) before bar(x) example worked because function bodies execute at compile/call-time instead of definition-time. However, it’s worth noting that some expressions inside function bodies do “execute” at definition-time, like variable scope declarations, macro calls, and nested function definitions:
julia> function foo()
x = Faz # executed at runtime, so defining Faz can wait
function bar(x::Baz) end # bar is defined when foo is defined
end
ERROR: UndefVarError: `Baz` not defined in `Main`